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

Posts Tagged ‘variable accessor’

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:

$foo = new Foo();

$funcname = 'dynamic_method';
$foo->$funcname();
// Same as calling $foo->dynamic_method();

$varname = 'dynamic_accessor';
$foo->$varname = 'some value';
// 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:

foo = Foo.new

funcname = 'dynamic_method'
foo.send "#{funcname}"
# same as calling foo.dynamic_method

varname = 'dynamic_accessor'
foo.send "#{varname}=", 'some value'
# 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