views:

74

answers:

1

I'm very new to Ruby (and OOP as well) and I don't know why the following thing doesn't work in Ruby

I extended the String class with a new method. Easy enough. Now I want to extend the Fixnum class. A String object appears somewhere in the class, but I can't use the method that I defined earlier. Why? Is this normal?

This is the new method for String:

class String

 public 
   def convert
 case self
   when "0" 
    "zero"
       when "1"
            "one"
         .
         .
         .
     end
   end
  end

And I would like to use it at one point when defining a new method for Fixnum.

+1  A: 

Did not understand your question. But from the snippet above I think you are walking in a no-need-to-be-that-complex direction, at least for the case statement :-)

Imagine you have the string "1"

First, to convert from "1" to 1, you have the to_i method. And you always have to_s to convert to String. If not, you still end with the to_s method from a plain object, which is more a debug value, but still.

Then, you have arrays, so you can take advantage of indexes.

words = ["zero", "one", "two", ... ]

so words[0] is "zero". Oh, they always match. And the input is "0", but input.to_i is 0. You got it.

def convert
 ["zero", "one", "two", ...][self.to_i]
end

And that is all.

Now, you can then have arrays for units, teens, tens, etc and perform the operations needed to assemble more complex words. The Linguistics gem does exactly that, allowing to do stuff like:

2004.en.numwords
# => "two thousand and four"

"cow".en.quantify( 20_432_123_000_000 )
# => "tens of trillions of cows"

I hope this was useful ;-)

duncan
Thanks for the answer. It was an interesting read. My yesterday's problem, however, was very trivial :)
Rafal