Skip to content

Instantly share code, notes, and snippets.

@IanWhitney
Last active August 29, 2015 14:10
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/b5c62ba7bd8c975f4461 to your computer and use it in GitHub Desktop.
Save IanWhitney/b5c62ba7bd8c975f4461 to your computer and use it in GitHub Desktop.
Struct and OpenStruct: Array conversions
# Array of an openstruct works as you'd expect, but to_a does not.
# OpenStruct descends from Object, Kernel, BasicObject. None of which implement to_a. So that explains that.
# I'm a little unclear on why Array(os) is working. Array(Object.new) works, and OpenStruct descends directly from Object.
# BUT, the Array docs say that it calls .to_ary or .to_a on the argument, and an OpenStruct instance responds to neither of those.
# So....?
require 'ostruct'
#=> true
os = OpenStruct.new
#=> #<OpenStruct>
os.prop1 = "test"
#=> "test"
os.prop2 = "value"
#=> "value"
Array(os)
#=> [#<OpenStruct prop1="test", prop2="value">]
os.to_a
#=> nil
# Array of a struct works the same as to_a on a struct, but neither is what you'd expect.
# This behavior is documented in the Struct documentation, but if you don't look at the docs, this might throw you.
MyStruct = Struct.new(:prop1, :prop2)
#=> MyStruct
x = MyStruct.new("test", "value")
#=> #<struct MyStruct prop1="test", prop2="value">
Array(x)
#=> ["test", "value"]
x.to_a
#=> ["test", "value"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment