Home > Net >  String to argument name
String to argument name

Time:11-18

Suppose I have a ruby function (func) with named arguments (foo and bar) which I can call by providing either or both arguments like this:

func(foo: "whatever")
func(bar: "whatever")
func(foo: "whatever", bar: "whatever")

What I need is a way to call this function by passing strings for the arguments' names:

name = "foo"
func(name: "whatever")

I read about to_sym but don't know how to use it. At least this does not work:

name = "foo"
func(name.to_sym: "whatever")

Is there a way?

Thanks.

CodePudding user response:

func(name.to_sym => "whatever")

Seems to work in Ruby 3.1

CodePudding user response:

You can use the following:

func("#{name}": "whatever")

The name will be interpolated and converted to symbol

  •  Tags:  
  • ruby
  • Related