Ruby Ruby 中的类型转换

ping94 · 2020年04月16日 · 最后由 ping94 回复于 2020年04月24日 · 5239 次阅读

常用类型转换方法

方法 目标类型 转换形式
#to_a Array 显式
#to_ary Array 隐式
#to_h Hash 显式
#to_hash Hash 隐式
#to_i Integer 显式
#to_int Integer 隐式
#to_s String 显式
#to_str String 隐式
#to_sym Symbol 隐式
#to_proc Proc 隐式

隐式转换方法

一般用于 源类型和目标类型很接近的情形。

有些情况 ruby 会隐式的在参数对象上调用隐式转换方法,以便得到预期的参数类型

ary = [1, 2, 3, 4]
a = 2.5
puts ary[a]  # => 3
class Position
    def initialize(idx)
        @index = idx
    end

    def to_int
        @index
    end
end
list = [1, 2, 3, 4, 5]
position = Position.new(2)
puts list[position] # => 3
puts list.at(position) # => 3

class Title
    def initialize(text)
        @text = text
    end

    def to_str
        @text
    end
end

title = Title.new("A Computer")
puts "Product Feature: " + title # => Product Feature: A Computer

我们在 Title 中实现了 #to_str 方法,它会暗示 Title 对象是一个 "类字符串" 对象,上述字符串拼接时会隐式的调用 #to_str 方法

显式转换方法

一般用于 源类型 和目标类型很大程度上不相干或毫无关联

ruby 核心类不会像调用 隐式方法 一样调用显式方法,显式方法是为开发人员准备的

Time.now.to_s # => "2020-04-16 00:00:00 +0800"

"string".to_i # => 0

字符串插值 是特例,ruby 会自动地调用显式类型转换方法 #to_s,将任何对象转换成字符串

class Title
    def initialize(text)
        @text = text
    end

    def to_s
        @text
    end
end

title = Title.new("A Computer")
puts "Product Feature: #{title}" # => Product Feature: A Computer

上述转换对于写容错性高的代码很有用出,有点像 JavaScript,当你想把字符串转换成数字的时候可以

[1] pry(main)> "helllo".to_i
=> 0
[2] pry(main)> "helllo".to_f
=> 0.0

如果找不到对应的数字就会返回0了,不会报错,如果想写更严谨的代码的话可以通过Integer, Float来做强制转换,找不到对应数值的时候会抛出异常

[3] pry(main)> Float("hello")
ArgumentError: invalid value for Float(): "hello"
from (pry):3:in `Float'
[4] pry(main)> Integer("hello")
ArgumentError: invalid value for Integer(): "hello"
from (pry):4:in `Integer'
[5] pry(main)> Integer("10.0")
ArgumentError: invalid value for Integer(): "10.0"
from (pry):5:in `Integer'
[6] pry(main)> Integer("10")
=> 10
[7] pry(main)> Float("10.0")
=> 10.0

PS:源自于《优雅的 Ruby》

实际使用中,把 "hello" 转换为数字的场景有吗?如果有,也应该转换为 0,而不应该显示错误。

sevk 回复

这个需要看各自的需求了

需要 登录 后方可回复, 如果你还没有账号请 注册新账号