0

Not sure is that ever possible, but it would be nice to optimize code this way. I'm trying to do something like this:

$name2 = 'name2'

def ('name1'+$name2)
...
end
5
  • 1
    Just to be sure, you want the name of the function to be dynamic? What is the use case? Commented May 27, 2018 at 11:40
  • 2
    Do not use global variables even in the examples. Also, you don’t want to name methods dynamically until you feel yourself a ruby guru, in 99% of tasks this is not needed. Commented May 27, 2018 at 12:35
  • @RoeeGavirel I Im already using variable name inside of the function, and want to use the same text for a function name too, to avoid repetition in further development. Commented May 27, 2018 at 13:13
  • Why do you need variable method names? What do you try to achieve? This sounds like a xy problem to me. Commented May 27, 2018 at 13:59
  • @spickermann heh, it looks like all my life is an xy problem))) ok, now I see that I need some array solution. but still looking for way to use just "name2" variations for array list, and leave function names inside looks: something+name2 Commented May 28, 2018 at 12:03

1 Answer 1

5

You can use define_method, here is an example:

>> foo = "bar"
=> "bar"
>> define_method("foo_#{foo}") do
?>   puts "Hello from method"
>> end
=> :foo_bar
>> foo_bar
=> Hello from method
Sign up to request clarification or add additional context in comments.

4 Comments

A comment on what __method__ is would be helpful.
Use __callee__ instead of __method__ unless you perfectly understand what are you doing. __method__ returns the name of the original method for aliases, which is confusing in most cases.
...or name = "bubba"; eval "def #{name}; 'hi'; end"; bubba #=> "hi". What's that flashing red light in my rear-view window? Oh, no, it's the eval police!
@CarySwoveland you're under arrest.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.