Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby class set/get

Tags:

ruby

set

get

What is wrong with this set/get?

class Pupil
  def name
    @name
  end

  def name=(name)
    @name = name
  end

  def age
    @age
  end

  def age=(age)
    @age
  end
end

Further on the same, if there was a child class with 3 arguments, name, age, sex, would the set get method in the child for sex only. Can you please show the set/get method and initialize in the child class.

like image 507
Selvam Avatar asked Jul 30 '12 06:07

Selvam


2 Answers

def age=(age)
    @age
  end

should be

  def age=(age)
    @age = age
  end

You can also make your code beautiful by replacing get/set with attr_accessor which itself provides a getter/setter

 class Pupil
   attr_accessor :age,:name
 end
like image 113
Pritesh Jain Avatar answered Oct 24 '22 08:10

Pritesh Jain


You forgot to set @age = age.

like image 33
Phil Aquilina Avatar answered Oct 24 '22 07:10

Phil Aquilina