Pippo
Pippo

Reputation: 925

Convert string to symbol/keyword

We can convert strings to symbols in the following way:

"string_to_symbol".to_sym
# => :string_to_symbol

How do I convert strings in the new way of defining keywords? Expected outcome:

# => string_to_symbol:

I call keywords dynamically, and I end up using => to assign a value to it. I prefer not to do it that way to keep my code consistent.

Upvotes: 0

Views: 346

Answers (1)

mhutter
mhutter

Reputation: 2916

No, there isn't.

It's important to note that these two lines do exactly the same:

{ foo: 'bar' }    #=> {:foo=>"bar"}
{ :foo => 'bar' } #=> {:foo=>"bar"}

This is because the first form is only Syntactic sugar for creating a Hash using a Symbol as the Key. (and not "the new way of defining keyword in ruby")

If you want to use other types as the key, you still have to use the "hashrocket" (=>):

{ 'key' => 'val' } #=> {"key"=>"val"}
{ 0 => 'val' }     #=> {0=>"val"}

Edit:

As @sawa noted in the comments, the question is about passing keyword arguments, not Hashes. Which is technically correct, but boils down to exactly the same (as long as it's Hashes with Symbols as keys:

def foo(bar: 'baz')
  puts bar
end

h = {
  :bar => 'Ello!'
}

foo(h)
# >> Ello!

Upvotes: 1

Related Questions