简体   繁体   English

如何在Ruby中将对象作为参数传递给其方法

[英]How to pass object as an argument to its method in Ruby

I'm trying to define factorial method for Fixnum class and I don't know how to pass this Fixnum as an argument to my method. 我正在尝试为Fixnum类定义阶乘方法,但我不知道如何将此Fixnum作为参数传递给我的方法。 Was trying to write something like that 试图写这样的东西

def Fixnum.factorial(n)
    n > 1 ? n * factorial(n-1) : 1
end

though I knew it would be incorrect. 虽然我知道那是不正确的。 So is there some kind of "this" reserved word to access this number? 那么,是否存在某种“此”保留字来访问此号码?

Something like this: 像这样:

class Fixnum
  def factorial
      self > 1 ? self * (self - 1).factorial : 1
  end
end

puts 6.factorial
# 720

You know, of course, that this is a silly method of calculating a factorial? 您当然知道这是计算阶乘的愚蠢方法吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM