0

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.

sawa
  • 165,429
  • 45
  • 277
  • 381
Pippo
  • 905
  • 11
  • 22
  • 2
    A keyword is not a Ruby object. You cannot create such thing. Anything passed to a method as a keyword would be referred to as a local variable. – sawa Aug 20 '15 at 17:14

1 Answers1

1

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!
mhutter
  • 2,800
  • 22
  • 30