【问题标题】:Ruby Method ChainingRuby 方法链
【发布时间】:2012-04-28 02:18:53
【问题描述】:

我想在 Ruby 中链接我自己的方法。而不是编写 ruby​​ 方法并像这样使用它们:

def percentage_to_i(percentage)
  percentage.chomp('%')
  percentage.to_i
end

percentage = "75%"
percentage_to_i(percentage)
=> 75

我想这样使用它:

percentage = "75%"
percentage.percentage_to_i
=> 75

我怎样才能做到这一点?

【问题讨论】:

  • 为什么不创建一个Percent 类?

标签: ruby chaining method-chaining


【解决方案1】:

您必须将方法添加到 String 类:

class String
  def percentage_to_i
    self.chomp('%')
    self.to_i
  end
end

这样你就可以得到你想要的输出:

percentage = "75%"
percentage.percentage_to_i # => 75

这有点没用,因为to_i 已经为你做了:

percentage = "75%"
percentage.to_i # => 75

【讨论】:

  • 哈哈,我最终这样做了,然后回来写我自己的答案。等待接受你的。谢谢。
  • 谢谢,问题更多是关于链接,但我不知道我可以单独使用 to_i 做同样的事情。
  • 我将该方法添加到 String 类(如您的答案中),但在模型文件 (app/models/content.rb) 中,在该模型的类定义的 end 语句之后。我认为这样做被称为“mixin”。
【解决方案2】:

你想要什么并不完全清楚。

如果您希望能够将String的实例转换为_i,那么只需调用to_i:

"75%".to_i  => 75

如果你想让它有一些特殊的行为,那么猴子补丁 String 类:

class String
    def percentage_to_i
        self.to_i    # or whatever you want
    end
end

如果你真的想要链接方法,那么你通常想要返回同一个类的修改实例。

class String
    def half
        (self.to_f / 2).to_s
    end
end

s = "100"
s.half.half   => "25"

【讨论】:

    【解决方案3】:

    单例方法

    def percentage.percentage_to_i
      self.chomp('%')
      self.to_i
    end
    

    创建自己的类

    class Percent
      def initialize(value)
        @value = value
      end
    
      def to_i
        @value.chomp('%')
        @value.to_i
      end
    
      def to_s
        "#{@value}%"
      end
    end
    

    【讨论】:

    • 有趣,什么时候比扩展类更有利?我正在尝试为单例方法所涉及的额外工作找出一个用例?
    • @Dru Singleton 实例上的方法在它们是一次性的东西时很有用。当我需要将对象变形为 API 以在库函数中使用时,我会使用它们,但并不经常需要它们。
    • 当实际上只有一个实例需要在类中未定义的不同行为时。这样做的好处是您不必更改类或扩展它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多