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
Don't Have Jekyll-Paginate or One of Its Dependencies Installed
Installing Ruby 2.3 on Wsl (Windows Subsystem for Linux)
Heroku: How to Push Seeds.Rb to Existing Rails App
Running Multiple Background Parallel Jobs with Rails
Do You Check in Your Rvmrc File
In Ruby, Should I Use ||= or If Defined? for Memoization
Rails 4 - Syntax Error, Unexpected Tidentifier, Expecting End-Of-Input
Why Relative Path Doesn't Work in Ruby Require
Jruby: Import VS Include VS Java_Import VS Include_Class
Polymorphic Association with Multiple Associations on the Same Model
Resetting a Singleton Instance in Ruby
Star Rating in Ajax with Ruby on Rails