How to call methods dynamically based on their name? [duplicate]

What you want to do is called dynamic dispatch. It’s very easy in Ruby, just use public_send: method_name=”foobar” obj.public_send(method_name) if obj.respond_to? method_name If the method is private/protected, use send instead, but prefer public_send. This is a potential security risk if the value of method_name comes from the user. To prevent vulnerabilities, you should validate which … Read more

Why is “slurping” a file not a good practice?

Again and again we see questions asking about reading a text file to process it line-by-line, that use variations of read, or readlines, which pull the entire file into memory in one action. The documentation for read says: Opens the file, optionally seeks to the given offset, then returns length bytes (defaulting to the rest … Read more

How to dynamically create a local variable?

You cannot dynamically create local variables in Ruby 1.9+ (you could in Ruby 1.8 via eval): eval ‘foo = “bar”‘ foo # NameError: undefined local variable or method `foo’ for main:Object They can be used within the eval-ed code itself, though: eval ‘foo = “bar”; foo + “baz”‘ #=> “barbaz” Ruby 2.1 added local_variable_set, but … Read more

Ruby ampersand colon shortcut [duplicate]

Your question is wrong, so to speak. What’s happening here isn’t “ampersand and colon”, it’s “ampersand and object”. The colon in this case is for the symbol. So, there’s & and there’s :foo. The & calls to_proc on the object, and passes it as a block to the method. In Ruby, to_proc is implemented on … Read more