Ruby - Classes

Defining a class

irb(main):001:0> class Greeter
irb(main):002:1>  def initialize(name = "World")
irb(main):003:2>   @name = name
irb(main):004:2>  end
irb(main):005:1>  def say_hi
irb(main):006:2>   puts "Hi #{@name}!"
irb(main):007:2>  end
irb(main):008:1>  def say_bye
irb(main):009:2>   puts "Bye #{@name}, come back soon"
irb(main):010:2>  end
irb(main):011:1> end
=> nil

The new keyword here is class. This defines a new class called Greeter and a bunch of methods for that class. Also notice @name. This is an instance variable, and is available to all the methods of the class. As you can see it is used by say_hi and say_bye.


Post a Comment

0 Comments