tags:

views:

330

answers:

2

What is the best way to create an alias to a instance atribute in Ruby (I'm not using rails or any ruby gem, just, Ruby).
For example given the class below, how can I create an alias to the :student_name attribute accessors?

class Student
  attr_accessor :student_name
  alias :name :student_name    #wrong
end

s = Student.new
s.student_name = "Jordan"
puts s.name  # --> Jordan
s.name = "Michael" # --> NoMethodError: undefined method `name=' for #<Student:0x572394> ...

Thank's guys!

+8  A: 

add

alias :name= :student_name=

this line of code only aliases the getter, not the setter method

alias :name :student_name    #wrong
John Douthat
+3  A: 

As John points out, you need to alias both the reader and the writer. This being Ruby, it's quite easy to define your own alias method to handle this for you.

class Module
  def attr_alias(new_attr, original)
    alias_method(new_attr, original) if method_defined? original
    new_writer = "#{new_attr}="
    original_writer = "#{original}="
    alias_method(new_writer, original_writer) if method_defined? original_writer
  end
end
Chuck