Kotaro Ezawa Kotaro Ezawa - 1 month ago 5
Ruby Question

What is wrong my code (trying to abbreviate)?

I am using irb/ruby1.9.1.

1st step



I wrote the code below:

def isUppercase
self>= ?A && self<= ?Z
end

class String
def abbreviate
abbr = ""
each_byte do |c|
if c.isUppercase
abbr += c.chr
end
end
abbr
end
end


2nd step



I am evaluating the code below which I expected to be "UFO".

"Unidentified Flying Object".abbreviate


However, errors occcured.
How do I correct it?
the error is here.

irb(main):044:0> load("abbrevi.rb")
=> true
irb(main):045:0> "Unidentified Flyng Object".abbreviate ArgumentError: comparison of Fixxnum with String failed
from C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:4:in >=' from
C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:4:in isUppercase' from
C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:12:in block in abbreviate' from
C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:11:in each_byte' from
C:/Ruby192/lib/ruby/1.9.1/abbrevi.rb:11:in abbreviate' from (irb):45 from
C:/Ruby192/bin/irb:12:in <main>

Answer

Try this:

class Fixnum
  def isUppercase
    self.chr >= ?A && self.chr <= ?Z
    #note use of `chr` to avoid error that occurs when
    #comparing a Fixnum to a String
  end
end

class String
  def abbreviate
    abbr = ""
    each_byte do |c|
      if c.isUppercase
        abbr += c.chr.to_s #note this usage as well
      end
    end
    abbr
  end
end

Note that you cannot add a string to a number, or compare, so the below will generate errors:

irb> 1 >= "A"
# => ArgumentError: comparison of Fixnum with String failed

UPDATE: @coreyward's answer is the better way to do what you're doing overall, but my answer is only pointing out how to fix your code and the reason for you error. A yet better way might be to use Regular Expressions.

Comments