在 Ruby 中使用方法时出现问题
我对 Ruby(以及 OOP)非常陌生,我不知道为什么以下内容在 Ruby 中不起作用
我用新方法扩展了 String 类。很容易。现在我想扩展 Fixnum 类。 String 对象出现在类中的某个位置,但我无法使用之前定义的方法。为什么?这是正常的吗?
这是 String 的新方法:
class String
public
def convert
case self
when "0"
"zero"
when "1"
"one"
.
.
.
end
end
end
我想在为 Fixnum 定义新方法时使用它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没明白你的问题。但从上面的代码片段来看,我认为您正朝着一个不需要那么复杂的方向前进,至少对于 case 语句来说是这样:-)
想象一下您首先有字符串“1”
,要从“1”转换到 1,你有 to_i 方法。而且你总是需要 to_s 来转换为字符串。如果没有,您仍然以普通对象的 to_s 方法结束,这更多的是一个调试值,但仍然如此。
然后,您就有了数组,因此您可以利用索引。
所以words[0]是“零”。哦,他们总是匹配的。输入是“0”,但 input.to_i 是 0。你明白了。
仅此而已。
现在,您可以拥有单位、十位数、十位数等数组,并执行组合更复杂单词所需的操作。 语言学瑰宝< /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.
so words[0] is "zero". Oh, they always match. And the input is "0", but input.to_i is 0. You got it.
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:
I hope this was useful ;-)