Ruby Warts

misfeatures and other problems
PERL| PHP| PYTHON| RUBY
Answers: (all questions)
Answer 1: (question)
Question:
#!/usr/bin/ruby

def dostuff()
  puts "dostuff"
end

class Test
  def dostuff()
    puts "Test.dostuff"
  end
  def run
    self.dostuff
    dostuff
  end
end

t = Test.new
t.run
Answer:
This program prints the following:
Test.dostuff
Test.dostuff
So, how can Test.run call the original dostuff(), which is shadowed?

According to #ruby-lang, "you can't". You must put the outer dostuff in a module, a class, or some other namespace and then access it explicitly, like "OtherClass.dostuff". Ruby is the only language I know of which cannot handle the case where class method names collide with their parent environment's methods. (C++ has a similar problem, but you can access the shadowed function by prepending a double colon to it -- ::dostuff();)

It seems odd that you'd have to call it explicitly, since ruby likes to eliminate explicit stuff where possible -- making "self." optional, for example, or "return". So, this seems inconsistent to me.

When I asked, I was basically told "you can't do that because it's bad design".
Answer 2: (question)
Question:
#!/usr/bin/ruby

class Book
  def open(path)
    @file = open(path)
  end
end

f = open("/dev/zero")
puts f

b = Book.new
b.open("/dev/zero")
puts b
Answer:
This program opens a file, prints the file's object ID, then crashes with a segmentation fault.

The reason it crashes is that Book.open calls itself recursively, until the stack overflows.

This is a double wart, because not only does the program recurse into oblivion, but it segfaults instead of raising an exception to handle the problem.
PERL| PHP| PYTHON| RUBY
Last modified: March 30, 2006 @ 5:53 MST
Copyright (C) 1996-2017 Selene Scriven