2

I use a specific library where I can pass variables with such an hash:

{ 'username' = > 'John'}

But when I try to pass the variables with such an hash:

{ 'username': 'John' }

It doesn't work. I always thought => is the old syntax for : but there seems to be really a difference.

Code where it's used: Liquid::Template.parse(template).render!(variables).html_safe

Can you please explain the difference and tell me how I can convert such an hash: { 'username': 'John' } to this { 'username' = > 'John'} presentation?

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
John Smith
  • 6,105
  • 16
  • 58
  • 109

1 Answers1

5
{ some_arbitrary_expression(some_argument, arg2) => another_arbitrary_expression(arg) }

Is the general syntax for Hash literals. Any object that responds to hash and eql? can be used as a key in a Hash.

{ some_valid_symbol: arbitrary_expression(arg1, arg2) }

Is the "new-style" Hash literal syntax for Symbol keys.

I always thought => is the old syntax for : but there seems to be really a difference.

I'm not sure where you were taught this, but I sure would like to know so I can warn others about this source. It has never been true, there are no current plans to make it true, and it probably never will be true. To my knowledge, there is nothing in the official documentation, in the RubySpec, or in any of the well-known books (The Ruby Programming Language, Programming Ruby) that says it either.

Can you please explain the difference and tell me how I can convert such an hash: { 'username': 'John' } to this { 'username' = > 'John'} presentation?

You can change the String representation of a Hash by monkey-patching Hash#to_s or Hash#inspect, but it is unclear what that would buy you.

If a method you are using expects a Hash whose keys are Strings and you pass it a Hash whose keys are Symbols, then changing the String representation of the Hash is not going to help you. You need to fix the source and make sure that your keys are Strings.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653