如何在Ruby中正确链接自定义方法? [英] How can I properly chain custom methods in Ruby?

查看:117
本文介绍了如何在Ruby中正确链接自定义方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为以下两种方法建立链接方法.运行此代码后,我不断获得以下输出:

I am trying to do a chaining method for the following two methods. After running this code, I kept getting the following output:

#<SimpleMath:0x007fc85898ab70>% 

我的问题是:Ruby中链接方法的正确方法是什么?

My question is: what is the proper way of chaining methods in Ruby?

这是我的代码:

class SimpleMath


    def add(a,b=0)
        a + b
        return self
    end


    def subtract(a,b=0)
         a - b
        return self
    end

end
newNumber = SimpleMath.new()
print newNumber.add(2,3).add(2)

推荐答案

您是否正在尝试执行类似的操作?

Are you trying to do something like this?

class SimpleMath
  def initialize
    @result = 0
  end

  #1 add function
  def add(val)
    @result += val
    self
  end

  #2 Subtract function
  def subtract(val)
    @result -= val
    self
  end

  def to_s
    @result
  end
end

newNumber = SimpleMath.new
p newNumber.add(2).add(2).subtract(1)

对于任意数量的参数

class SimpleMath
  def initialize
    @result = 0
  end

  #1 add function
  def add(*val)
    @result += val.inject(&:+)
    self
  end

  #2 Subtract function
  def subtract(*val)
    @result -= val.inject(&:+)
    self
  end

  def to_s
    @result
  end
end

newNumber = SimpleMath.new
p newNumber.add(1, 1).add(1, 1, 1, 1).subtract(1)

这篇关于如何在Ruby中正确链接自定义方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆