我的代码有什么问题(试图缩写)?
我正在使用 irb/ruby1.9.1。
第一步
我写了下面的代码:
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
第二步
我正在评估下面的代码,我希望它是“UFO”。“不明飞行物”.abbreviate
但是,出现了错误。 我该如何纠正它? 错误就在这里。
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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
请注意,您不能将字符串添加到数字或进行比较,因此以下内容将生成错误:
更新: @coreyward 的答案是完成您正在做的事情的更好方法,但是我的回答只是指出如何修复您的代码以及错误的原因。更好的方法可能是使用正则表达式。
Try this:
Note that you cannot add a string to a number, or compare, so the below will generate errors:
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.
我不明白为什么您要检查字节是否为大写,而不是字符(存在多字节字符),但这完全回避了您的问题:
不过,这仍然没有真正考虑到非 AZ 字母/字符。
I don't see why you're checking if a byte is uppercase, rather than a character (there are multi-byte characters), but this sidesteps your issue entirely:
This still doesn't really take non A-Z letters/characters into account, though.