Yeah I am a lame PHP guy who hasn’t gotten too deeply into Ruby yet. ;)
In PHP I often use variable methods, for example:
3 | $funcname = 'dynamic_method' ; |
7 | $varname = 'dynamic_accessor' ; |
8 | $foo -> $varname = 'some value' ; |
Now, because Ruby does not prefix $ in front of variables, it is impossible to use variable methods the way we do in PHP.
I am sure for Ruby gurus it’s pretty obvious but for me, I just spent more than 30 minutes searching for an alternative other than evil eval, and I finally found one.
We use the PHP call_user_func and call_user_func_array equivalent in Ruby: send or __send__.
Luckily accessors in Ruby are methods, so we are able to use the send method for both methods and accessors.
For example we can set a variable accessor like this:
3 | funcname = 'dynamic_method' |
7 | varname = 'dynamic_accessor' |
8 | foo.send "#{varname}=" , 'some value' |
I wish in future versions of Ruby, we can somehow assign accessor values the way we do in PHP. :)
Related posts