Weird stuff in Ruby

Lately I’ve stumbled over interesting feature of Ruby syntax. Essentially Ruby allows to define a method inside a class for another class. Like this.

1
2
3
4
5
6
7
8
9
10class A
end

class B
  def A.boom!
    puts 'Boom!'
  end
end

A.boom!

And it works!

Boom!

Also it doesn’t understand modules in the def clause.

1
2
3
4
5
6
7
8
9
10class C::A
end

class B
  def C::A.boom!
    puts 'Boom!'
  end
end

C::A.boom!
5: syntax error, unexpected '.', expecting '\n' or ';'
  def C::A.boom!
          ^
8: syntax error, unexpected kEND, expecting $end

I’ve googled a bit but couldn’t find anything about that.

And here’s another interesting tidbit about this. It looks like method is beign transplanted to explicit class right away.

1
2
3
4
5
6
7
8
9
10
11
12class A
  @boom = 'Boom!'
end

class B
  @boom = 'Yada yada'
  def A.boom!(str = @boom)
    puts str
  end
end

A.boom!

You might guess the result already.

Boom!

If anybody know anything about this behavior I’d be appreciate for pointers.

Mon, 17 May, 2010, 20:35
Tags: