Skip to content

Instantly share code, notes, and snippets.

@IanWhitney
Last active September 12, 2015 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IanWhitney/92065f03c0bdf30fd480 to your computer and use it in GitHub Desktop.
Save IanWhitney/92065f03c0bdf30fd480 to your computer and use it in GitHub Desktop.
# From the docs of Kernel.array
# First tries to call to_ary on arg, then to_a.
# http://ruby-doc.org/core-2.2.3/Kernel.html#method-i-Array
# Ok, so does a struct respond to to_ary?
Monkey = Struct.new(:name, :favorite_color)
m = Monkey.new("George", "Yellow")
m.respond_to?(:to_ary)
#=> false
# So, does it respond to to_a?
m.respond_to?(:to_a)
#=> true
# And what is the behavior of struct's .to_a?
# Returns the values for this struct as an Array.
# http://ruby-doc.org/core-2.2.3/Struct.html#method-i-to_a
# So...
m.to_a
#=> ["George", "Yellow"]
# and
Array(m)
#=> ["George", "Yellow"]
# maybe not the principle of least surprise, but it makes sense when you dig in.
# What about non-structs?
Array(1)
#=> [1]
# so, to_ary?
1.respond_to(:to_ary?)
#=> false
# Ok, to_a?
1.respond_to(:to_a?)
#=> false
# ...ok...so?
# https://github.com/ruby/ruby/blob/f830ace8a831a954db7a6aae280a530651a5b58a/object.c#L3133
# ¯\_(ツ)_/¯
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment