O'Reilly logo

Ruby on Rails For Dummies® by

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

Hashes

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
    10
  end
end

my_object = MyClass.new
print my_object.my_method, " "

class MyClass
  def another_method
    22
  end
end

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required