在 Ruby 中有没有办法重载初始化构造函数? [英] In Ruby is there a way to overload the initialize constructor?

查看:46
本文介绍了在 Ruby 中有没有办法重载初始化构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,您可以重载构造函数:

In Java you can overload constructors:

public Person(String name) {
  this.name = name;
}
public Person(String firstName, String lastName) {
   this(firstName + " " + lastName);
}

Ruby 有没有办法实现同样的结果:两个构造函数采用不同的参数?

Is there a way in Ruby to achieve this same result: two constructors that take different arguments?

推荐答案

答案是肯定的和否定的.

The answer is both Yes and No.

您可以使用各种机制获得与在其他语言中相同的结果,包括:

You can achieve the same result as you can in other languages using a variety of mechanisms including:

  • 参数的默认值
  • 变量参数列表(splat 运算符)
  • 将参数定义为散列

语言的实际语法不允许你定义一个方法两次,即使参数不同.

The actual syntax of the language does not allow you to define a method twice, even if the arguments are different.

考虑到上述三个选项,这些可以通过您的示例实现,如下所示

Considering the three options above these could be implemented with your example as follows

# As written by @Justice
class Person
  def initialize(name, lastName = nil)
    name = name + " " + lastName unless lastName.nil?
    @name = name
  end
end


class Person
  def initialize(args)
    name = args["name"]
    name = name + " " + args["lastName"] unless args["lastName"].nil?
    @name = name
  end
end

class Person
  def initialize(*args)
    #Process args (An array)
  end
end

您会在 Ruby 代码中经常遇到第二种机制,尤其是在 Rails 中,因为它提供了两全其美的优势,并允许使用一些语法糖来生成漂亮的代码,尤其是不必将传递的哈希值括在大括号中.

You will encounter the second mechanism frequently within Ruby code, particularly within Rails as it offers the best of both worlds and allows for some syntactic sugar to produce pretty code, particularly not having to enclose the passed hash within braces.

这个wikibooks 链接提供了更多阅读内容

This wikibooks link provides some more reading

这篇关于在 Ruby 中有没有办法重载初始化构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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