More Neat Things About Ruby

This section is a continuation of "ruby intro", covering more advanced topics. It is still intended as a brief, lightweight overview of the Ruby language; following sections will cover all these topics in much more detail.

Reopening classes

class Fixnum
  def divisible_by? n
    self % n == 0
  end
end

4.divisible_by? 2 #=> true
4.divisible_by? 3 #=> false

Duck Typing

Modules and Mixins

Array Assignment

@width, @height = width, height
@width, @height = [width, height]

def dimensions
  [10, 20]
end
@width, @height = dimensions

Metaprogramming

Classes are objects

Domain-Specific Languages (DSLs)

No Function Overloading

Operators are Methods

Equivalent:

1 + 2
1.+(2)
1.send "+", 2

send the object 1 the message + with the parameter 2

Operator Overriding

"abc" * 3           #=> "abcabcabc"
"abc" << "def"      #=> "abcdef"
"%d live crew" % 2  #=> "2 live crew"

Next Lesson 

Outline

[menu]

/