Read the latest web development and design tips at Fred Wu's new blog! :-)
Poke me on GitHub

Posts Tagged ‘variable method’

Variable methods and accessors in Ruby

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:

1$foo = new Foo();
2 
3$funcname = 'dynamic_method';
4$foo->$funcname();
5// Same as calling $foo->dynamic_method();
6 
7$varname = 'dynamic_accessor';
8$foo->$varname = 'some value';
9// Same as calling $foo->dynamic_accessor = '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:

1foo = Foo.new
2 
3funcname = 'dynamic_method'
4foo.send "#{funcname}"
5# same as calling foo.dynamic_method
6 
7varname = 'dynamic_accessor'
8foo.send "#{varname}=", 'some value'
9# same as calling foo.dynamic_accessor = 'some value'

I wish in future versions of Ruby, we can somehow assign accessor values the way we do in PHP. :)

Related posts