About modifying core classes

Hello,

I started to learn ruby after reading this nasty article about PHP:
PHP: a fractal of bad design / fuzzy notepad what bothered
me more was the unpredictability and uncertainty that could arise from
some PHP settings and constructs. So I felt it might be a good time to
find another language a little more deterministic.

I just finished a Ruby tutorial on Lynda.com but there is something that
bothers me and is the fact that Ruby allows you to overwrite the
functionality of core classes, at first glance it looks like a really
good feature but… say for example that you have this code:

integer_array = [1,3,5,7,9,18,36,64,128]

sum = 0

integer_array.each do |item|
  sum += item
end

puts sum

(I know I could have used inject for this but this is just an example).

Everything works nice and tidy I get my sum which is 271. Then I decide
to include a library that does some really useful thing into my
application, but for some reason the author of the library decided that
is more convenient for him if he could get the index of the item inside
the each block so he decides to modify the Array class like this:

class Array
  def each
    i = 0;
    n = self.length

    while i < n do
      yield i, self[i]
      i += 1
    end
  end
end

(forgive me if my code is not very stylish I’m a Ruby beginner)

So, anyways, the above code stills runs, but the sum I get now is 36, no
error, no warnings, nothing… I was expecting to get an argument error
(2 for 1) or something like that but nothing… and this will probably
wont pop up in unit tests because I would probably be using a mock
object instead of the actual library.

I suppose (or at least hope) that every “Ruby best practices” document
says that you SHOULDN’T do something like this but you cannot rule out
the possibility of encountering a bad programmer out there.

So, I would like to hear your thoughts on this… should this be a
source of concern? How can you be certain that you code will do what you
expect it to do if any library can change the way the core objects of
the language works and behave?