Ruby Convert String to Method Name

Ruby convert string to method name

Best way is probably:

methods.each { |methodName| send(methodName, 'abc') }

See Object#send

String to method name

method(action).call

or

public_send(action)

Example:

method(action).call
#=> James
public_send(action)
#=> James

Be aware, though, that none of the above cares about the context, where was method originally defined, so both will call it in the context of the current object.

Ruby convert string to method name of another class

[MobileConfiguration::DISCLAIMERS].each do |property|
configuration.public_send("#{property}=",test_app.public_send(property))
end

can be used to copy values from one model to another for preferences.

Calling a Method From a String With the Method's Name in Ruby

To call functions directly on an object

a = [2, 2, 3]
a.send("length")
# or
a.public_send("length")

which returns 3 as expected

or for a module function

FileUtils.send('pwd')
# or
FileUtils.public_send(:pwd)

and a locally defined method

def load()
puts "load() function was executed."
end

send('load')
# or
public_send('load')

Documentation:

  • Object#public_send
  • Object#send

How do I convert a string to a class method?

Post.send(anything)

How to turn a string into a method call?

Object#send

>> a = "class"
>> "foo".send(a)
=> String

>> a = "reverse"
>> "foo".send(a)
=> "oof"

>> a = "something"
>> "foo".send(a)
NoMethodError: undefined method `something' for "foo":String

Ruby convert string to keyword argument

You can use the .to_sym method. This is ruby function method that convert string to symbol.

Or using rails own, "symbol name".parameterize.underscore.to_sym. This will convert the string to :symbol_name. This uses rails naming convention.

convert string into class name in rails

You should use constantize to get a class based on it's name in string:

"FlightManager::#{handler.camelize}".constantize.calculate())


Related Topics



Leave a reply



Submit