Hash vs block

why is it that as soon as you call puts it turns the hash into a block?

hash

{ 1 => 1}

block

puts {1=>1}

I feel like this should still be a hash, there is an example on the ruby
docs that doesnt work that showcases the difference here:

require ‘json’

my_hash = {:hello => “goodbye”}
puts JSON.generate(my_hash)

This does not work, yet its documented @

I’m not quite sure what you are asking, but the example you link to is,
as you write, a bit wrong. Try it in IRB without the puts, and you’ll
see it will output the expected JSON string

irb(main):001:0> require ‘json’
=> true
irb(main):002:0> my_hash = {:hello => “goodbye”}
=> {:hello=>“goodbye”}
irb(main):003:0> JSON.generate(my_hash)
=> “{“hello”:“goodbye”}”

Sorry, I did a poor job of explaining. The lack of clarity for me is
where a hash turns into a block when you call puts on it. There is an
example on ruby docs using json where they use:

require ‘json’
puts {:hello => “goodbye”}.to_json

This actually returns an error:

require ‘json’
=> true
irb(main):013:0> puts {:hello => “goodbye”}.to_json
SyntaxError: (irb):13: syntax error, unexpected =>, expecting ‘}’
puts {:hello => “goodbye”}.to_json

Upon further investigation this wont even work:
puts {:hello => “goodbye”}
SyntaxError: (irb):10: syntax error, unexpected =>, expecting ‘}’
puts {:hello => “goodbye”}

yet this works:
puts “hello” => “goodbye”
{“hello”=>“goodbye”}
=> nil

this is a hash:
{ 1 => 1}.class
=> Hash

and now its a block:
puts { 1 => 1}.class
SyntaxError: (irb):8: syntax error, unexpected =>, expecting ‘}’
puts { 1 => 1}.class

I dont get how it goes from class hash to class block, its like magic

Oh, okay, so that was the question.

I really don’t have a good answer for you, other than it being the
tokenizer, which interprets the { as starting a block instead of
starting a hash.

It works with

irb(main):009:0> puts :hello => “world”
{:hello=>“world”}
=> nil

because the interpreter sees it as a hash, and passes that to the method
puts.

In the case of

irb(main):010:0> puts { :hello => “world” }
SyntaxError: (irb):10: syntax error, unexpected =>, expecting ‘}’
puts { :hello => “world” }
^
from /Users/ohm/.rbenv/versions/2.2.0/bin/irb:11:in `’

The interpreter sees the { and thinks it’s the beginning of a block
instead, trying to do something meaningful with it and failing.

If you want the original to work, you can wrap it in parentheses:

irb(main):011:0> puts({:hello => “world”})
{:hello=>“world”}
=> nil