DEV Community

Burdette Lamar
Burdette Lamar

Posted on

Ruby Question

The documentation for method :to_h in Ruby class OpenStruct says this:

Converts the OpenStruct to a hash with keys representing each attribute (as symbols) and their corresponding values.

If a block is given, the results of the block on each pair of the receiver will be used as pairs.

And it offers this example:

require "ostruct"
data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
data.to_h   # => {:country => "Australia", :capital => "Canberra" }
data.to_h {|name, value| [name.to_s, value.upcase] }
            # => {"country" => "AUSTRALIA", "capital" => "CANBERRA" }

When I do the same in irb (version: irb 0.9.6(09/06/30)), I get this:

require "ostruct"
# => true
data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
# => #<OpenStruct country="Australia", capital="Canberra">
data.to_h
# => {:country=>"Australia", :capital=>"Canberra"}
data.to_h {|name, value| [name.to_s, value.upcase] }
# => {:country=>"Australia", :capital=>"Canberra"}

The difference:

  • In the documentation, the last two values are different.
  • In the irb session, they are the same.

So, my question: Is this a documentation error?

Top comments (3)

Collapse
 
rhymes profile image
rhymes • Edited

What Ruby version are you using?

I've tried with Ruby 2.6.3 and it behaves exactly like in the documentation:

2.6.3 :001 > require "ostruct"
 => true
2.6.3 :002 > data = OpenStruct.new("country" => "Australia", :capital => "Canberra")
 => #<OpenStruct country="Australia", capital="Canberra">
2.6.3 :003 > data.to_h
 => {:country=>"Australia", :capital=>"Canberra"}
2.6.3 :004 > data.to_h {|name, value| [name.to_s, value.upcase] }
 => {"country"=>"AUSTRALIA", "capital"=>"CANBERRA"}

With Ruby 2.5.1 it behaves like in your example:

2.5.1 :004 > data.to_h {|name, value| [name.to_s, value.upcase] }
 => {:country=>"Australia", :capital=>"Canberra"}

If you check Ruby 2.5.1's version of the documentation - ruby-doc.org/stdlib-2.5.1/libdoc/o... - you'll notice that data.to_h does not support the additional block, that's why it returns the unchanged format.

Collapse
 
burdettelamar profile image
Burdette Lamar

Wow! Thanks, @rhymes ! I have 2.5.3 installed, so you're correct. Looking over at rubyinstaller.org/, I see the recommendation to stay with 2.5 for now.

For the post I'm writing, I think I'll specify which Ruby version I'm writing about.

Collapse
 
rhymes profile image
rhymes

Yeah, unfortunately Ruby's support on Windows isn't great :(