Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between to_a and to_ary?

Tags:

ruby

What's the difference between to_a and to_ary?

like image 794
hey mike Avatar asked Feb 27 '12 15:02

hey mike


2 Answers

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:

  • Ruby Issue 3680
  • Variables
like image 169
Matheus Moreira Avatar answered Sep 18 '22 20:09

Matheus Moreira


to_ary allows an object to be treated as an array, whereas to_a actually tries to convert the parameter into an array.

to_ary can be useful for parallel assignment, whereas to_a is more suited for an actual conversion.

like image 34
siame Avatar answered Sep 19 '22 20:09

siame