Skip to content

codyrobbins/easier-instance-variable-access

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Easier Instance Variable Access

Ruby’s built-in Object#instance_variable_get and #instance_variable_set methods are clunky to use because you have to unnecessarily prepend an ‘@’ to the name of the instance variable you pass in—which usually leads to much less readable code in the contexts in which I tend to use these methods. On top of that, they’re poorly named: the method names don’t read like English.

This gem adds two methods to Object that fix these problems: instance_variable method to replace instance_variable_get and set_instance_variable method to replace instance_variable_set.

Full documentation is at RubyDoc.info.

Examples

These methods are only available within an instance of a class—like the corresponding built-in Ruby methods—so the following examples are given in that context.

The usual Ruby way

instance_variable_get('@user')
instance_variable_set('@user', new_value)

name = :user
instance_variable_get("@#{name}")
instance_variable_set("@#{name}", new_value)

Using easier-instance-variable-access

instance_variable(:user)
set_instance_variable(:user, new_value)

name = :user
instance_variable(name)
set_instance_variable(name, new_value)

Colophon

See also

If you like this gem, you may also want to check out To Class.

Tested with

  • Ruby 1.9.2-p180 — 20 May 2011

Contributing

To send patches, please fork on GitHub and submit a pull request.

Credits

© 2011 Cody Robbins. See LICENSE for details.

About

Access instance variables in Ruby the way you should be able to.

Resources

License

Stars

Watchers

Forks

Languages