Ruby class shortcuts

class Person
  attr_accessor :name, :age
end

# same as:

class Person
  def name
    @name 
  end

  def name=(name)
    @name = name
  end

  def age 
    @age
  end

  def age=(age)
    @age = age
  end 
end

Ruby is awesome. I think it has to do with the ease and beauty of Textmate but I really look forward to typing out code using the language. Additionally I’ve been introduced to many shortcuts which make writing code a lot easier.

One recent shortcut which I’ve been trying to wrap my head around is attraccessor. In the above code you will see the one line “attraccessor :name, :age” re-writes everything below.

It basically performs the read and write methods on a function. This allows you to call x.name and return whatever x is and also allows you to assign x.name = “Jahde”.

I’m sure I’ll be seeing other shortcuts that make writing code easier but this one stood out to me. I think I’m just shocked that 1 line can replace 12 but I’ve come to find this is one of the key attributes of programming itself. Ruby wants to make herself easy to love.

 
0
Kudos
 
0
Kudos

Now read this

What every Ruby developer should know before learning Javascript

How to transition from Ruby to Javascript in one day # My new bae is named JavaScript ???— Lone Wolf (@jahde) May 14, 2015 After inundating myself with Ruby for close to six consecutive weeks it was time for us to go on a break. We had... Continue →