to_a
との違いは何ですかto_ary
?
ベストアンサー1
to_ary
使用される用途暗黙to_a
変換は、明示的な変換。
例えば:
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)>
スプラット演算子(*
)は、明示的な配列への変換:
c2 = Coordinates.new *c
# to_a called
# => #<Coordinates (10, 20)>
一方、並列割り当ては、暗黙配列への変換:
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
。
to_s
このパターンは、やto_str
、to_i
やto_int
などのメソッドのペアからもわかるように、Ruby 言語全体で使用されているようです。
参考文献: