Ruby Method Chaining

浪子不回头ぞ 提交于 2019-12-10 17:23:00

问题


I would like to chain my own methods in Ruby. Instead of writing ruby methods and using them like this:

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

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

I would like to use it like this:

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

How can I achieve this?


回答1:


You have to add the method to the String class:

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

With this you can get your desired output:

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

It's kind of useless, because to_i does it for you already:

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



回答2:


It's not completely clear what you want.

If you want to be able to convert an instance of String to_i, then just call to_i:

"75%".to_i  => 75

If you want it to have some special behavior, then monkey patch the String class:

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

And if you truly want to chain methods, then you typically want to return a modified instance of the same class.

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

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



回答3:


Singleton methods

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

creating your own class

class Percent
  def initialize(value)
    @value = value
  end

  def to_i
    @value.chomp('%')
    @value.to_i
  end

  def to_s
    "#{@value}%"
  end
end


来源:https://stackoverflow.com/questions/10360051/ruby-method-chaining

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!