Chapter 15. Ten Features That Set Ruby Apart

In This Chapter

  • Exploring Ruby's oddities

  • Using mixins, unit testing, and other stuff

  • Quacking like a duck

This chapter highlights some of Ruby's unique features. I list the features in no particular order. I cover many of these features in Chapters 5 and 6, but a few of this chapter's features blaze new Ruby territory.


A hash is a collection of key/value pairs. Use curly braces {} to define a hash; use brackets [] to refer to a particular hash value.

price_of = 
  {'Book' => 20.00, 'Shirt' => 15.05, 'Cup' => 10.20}
price_of['Car'] = 23999.99

puts price_of['Car']

The output of this brief program is 23999.99.

For more info, see Chapter 5.

Open Classes

You can add definitions to a class at any point in the code. For example, in the following program, the definition of MyClass ends before the creation of my_object. Then the MyClass definition resumes after the creation of my_object.

class MyClass
  def my_method

my_object =
print my_object.my_method, " "

class MyClass
  def another_method

print my_object.another_method

The output of this program is 10 22.

For more on open classes, see Chapter 6.

Duck Typing

If it walks like a duck and it quacks like a duck, then it's a duck. Consider the following program. At first, the value variable walks and quacks like an integer. At that point in the code, value is an integer. So value.times is legal but value.each is illegal. (If you uncomment the first value.each line and try to ...

Get Ruby on Rails For Dummies® now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.