在 Ruby 中使用方法时出现问题

发布于 2024-08-31 08:14:27 字数 386 浏览 10 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

兮子 2024-09-07 08:14:27

没明白你的问题。但从上面的代码片段来看,我认为您正朝着一个不需要那么复杂的方向前进,至少对于 case 语句来说是这样:-)

想象一下您首先有字符串“1”

,要从“1”转换到 1,你有 to_i 方法。而且你总是需要 to_s 来转换为字符串。如果没有,您仍然以普通对象的 to_s 方法结束,这更多的是一个调试值,但仍然如此。

然后,您就有了数组,因此您可以利用索引。

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

所以words[0]是“零”。哦,他们总是匹配的。输入是“0”,但 input.to_i 是 0。你明白了。

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

仅此而已。

现在,您可以拥有单位、十位数、十位数等数组,并执行组合更复杂单词所需的操作。 语言学瑰宝< /a> 正是这样做的,允许做类似的事情:

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

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

我希望这有用;-)

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 ;-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文