Ruby类型转换

Ruby强制类型转换

Ruby 中常用的类型转换方法:

方法 目标类型 转换形式
#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 # => "2022-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