40
to_ary
is used for implicit conversions, while to_a
is used for explict conversions.
to_ary用于隐式转换,而to_a用于explict转换。
For example:
例如:
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
# => #
The splat operator (*
) is a form of explicit conversion to array:
splat运算符(*)是一种显式转换为数组的形式:
c2 = Coordinates.new *c
# to_a called
# => #
On the other hand, parallel assignment is a form of implicit conversion to array:
另一方面,并行赋值是一种隐式转换为数组的形式:
x, y = c
# to_ary called
puts x
# 10
puts y
# 20
And so is capturing collection members in block arguments:
在块参数中捕获集合成员也是如此:
[c, c2].each { |(x, y)| puts "Coordinates: #{x}, #{y}" }
# to_ary called
# Coordinates: 10, 20
# to_ary called
# Coordinates: 10, 20
Examples tested on ruby-1.9.3-p0
.
在ruby-1.9.3-p0上测试的实施例。
This pattern seems to be used all over the Ruby language, as evidenced by method pairs like to_s
and to_str
, to_i
and to_int
and possibly more.
这种模式似乎在整个Ruby语言中使用,如to_s和to_str,to_i和to_int等可能更多的方法对所证明。
References:
参考文献:
- Ruby Issue 3680
- Ruby Issue 3680
- Variables
- 变量