Sep 25, 2009

More Ruby Shortcuts

Class Getter and Setter

class Vehicle
  def model
    @model
  end


  def model=(model)
    @model = model
  end
end

or shortcut would be (equivalent to above):

class Vehicle
  attr_accessor :model
end

Possible attributes are attr_reader (getter only), attr_writer (setter only) and attr_accessor (both get/set)

Conditionals

We can use ? symbol as part of the name of the method such as

def purchased?
  ...
end

normally we do this way:

if purchased? then puts "Thank you" end
if not purchased? then puts "Want to buy?" end 
#can also use !purchased? to negate it




we can also make it more compact and readable:

puts "Thank you" if purchased?
puts "Want to buy?" unless purchased?



No comments:

Post a Comment