Today I Learned

hashrocket A Hashrocket project

Difference betweent `to_a` and `to_ary`

  • to_a => called for explicit conversions
  • to_ary => called for implicit conversions

example:

class Coordinates
  attr_reader :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
end

coordinates = Coordinates.new(5, 7)

puts "splat"
a = *coordinates
# => to_a called

puts "multiple assignment"
x, y = coordinates
# => to_ary called

puts "Implicit conversion into block params"
[coordinates].each { |(x, y)| puts x }
# => to_ary called
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.