In Ruby, is there a way to do something like
class Foo
attr_reader :var_name :reader_name #This won't work, of course
def initialize
@var_name = 0
end
end
# stuff here ....
def my_method
foo = Foo.new
assert_equal 0,foo.reader_name
end
In other words, is there a standard way to make an accessor method for a variable that uses a different name than the variable. (Besides hand-coding it, of course.)
You could use
alias_method:The
var_namemethod built byattr_readerwould still be available though. You could useremove_methodto get rid of thevar_namemethod if you really wanted to (but make sure you get everything in the right order):If you really wanted to, you could monkey patch an
attr_reader_asmethod into Module:A better
attr_reader_aswould take a hash (e.g.{ var_name: :reader_name, var_name: :reader_name2}) but I’ll leave that as an exercise for the reader.