to_ary
用于implicit次转换,而to_a
用于explict次转换.
例如:
class Coordinates
attr_accessor :x, :y
def initialize(x, y); @x, @y = x, y end
def to_a; puts 'to_a called'; [x, y] end
def to_ary; puts 'to_ary called'; [x, y] end
def to_s; "(#{x}, #{y})" end
def inspect; "#<#{self.class.name} #{to_s}>" end
end
c = Coordinates.new 10, 20
# => #<Coordinates (10, 20)>
splat运算符(*
)是explicit转换为数组的一种形式:
c2 = Coordinates.new *c
# to_a called
# => #<Coordinates (10, 20)>
另一方面,并行赋值是implicit到数组的转换形式:
x, y = c
# to_ary called
puts x
# 10
puts y
# 20
在块参数中捕获集合成员也是如此:
[c, c2].each { |(x, y)| puts "Coordinates: #{x}, #{y}" }
# to_ary called
# Coordinates: 10, 20
# to_ary called
# Coordinates: 10, 20
对ruby-1.9.3-p0
个样本进行测试.
这种模式似乎在Ruby语言中被广泛使用,to_s
和to_str
、to_i
和to_int
等方法对以及可能更多的方法就证明了这一点.
参考资料: