如何使特定方法在Ruby中使用不同数量的参数?

时间:2014-10-30 22:03:35

标签: ruby class module

我希望我的方法add_directory能够使用一个或两个参数。如该方法的两个不同版本所示。我知道Ruby不允许方法重载,而作为来自C++的人我还没有掌握它。如何重新设计我的方法以便实现我想要的结果?提前致谢。


Module RFS
  class Directory
   attr_accessor :content
   def initialize
     @content = {}
   end

   def add_file (name,file)
     @content[name]=file
   end

   def add_directory (name,subdirectory)
     @content[name] = subdirectory
   end

   def add_directory (name)
     @content[name] = RFS::Directory.new
   end
 end
end

2 个答案:

答案 0 :(得分:0)

您的案例中有几种可能的解决方案。最简单的一种,可能是最正确的,是将subdirectory声明为可选参数。

def add_directory(name, subdirectory = nil)
  if subdirectory
    @content[name] = subdirectory
  else
    @content[name] = RFS::Directory.new
  end
end

在Ruby中,您可以使用*(splat)运算符模拟重载并检查方法中的参数。例如

def add_directory(*names)
  # here *names is an array of 0 or more items
  # you can inspect the number of items and their type
  # and branch the method call accordingly
end

但是这种解决方案在你的情况下是不必要的复杂。

答案 1 :(得分:0)

噢,男人,Simone在我回答的时候得到了它。

我打算建议

def add_directory(name, subdirectory=nil)
  @content[name] = subdirectory.present? ? subdirectory : RFS::Directory.new
end

回应Simone的splat方法。

def add_directory(*args)
  @content[args[0]] = args.length > 1 ? args[1] : RFS::Directory.new
end

我个人并不喜欢这样,因为你有一个必需的name参数,然后是一个可选的subdirectory参数。你不会知道他们是将名字放在第一位还是第二位,或者他们是否放了名字。最好是将名字作为第一个参数并在splat中捕获其余的参数

def add_directory(name, *args)
  @content[name] = args.present? ? args[0] : RFS::Directory.new
end

结果类似于第一种只将子目录设置为默认值为nil的方法