add method to class

By hawker on Aug 24, 2005

This time a greeting is printed using an object-oriented
approach.

# Add a new method (function) to class String.
# After we do this, all strings will know how to greet.
class String
  def greet
    puts "Hello, #{self}!"
  end
end

class Integer
  def greet
    self.times { puts "Hi, whoever you are." }
  end
end

# Now an integer has a different way of greeting than
# a string does.

"Tom".greet
3.greet

Comments

Sign in to comment.
Hawkee   -  Aug 24, 2005

Neat, I really like the object oriented structure of Ruby.

 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.