Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

ruby - What's the difference between to_a and to_ary?

What's the difference between to_a and to_ary?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

to_ary is used for implicit conversions, while to_a is used for explict conversions.

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
# => #<Coordinates (10, 20)>

The splat operator (*) is a form of explicit conversion to array:

c2 = Coordinates.new *c
# to_a called
# => #<Coordinates (10, 20)>

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.

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.

References:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...