Last active
September 12, 2015 02:23
-
-
Save IanWhitney/92065f03c0bdf30fd480 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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