gpt4 book ai didi

ruby-on-rails - Rails 可选参数

转载 作者:数据小太阳 更新时间:2023-10-29 06:22:06 26 4
gpt4 key购买 nike

我有课

class Person
attr_accessor :name,:age
def initialize(name,age)
@name = name
@age = age
end
end

我想将年龄设为可选,如果未通过则为 0,如果未通过则名称为空白

我对此进行了一些研究,但对于我发现的内容有点困惑(必须在另一个变量 { } 中传递变量)。

最佳答案

就这么简单:

class Person
attr_accessor :name, :age

def initialize(name = '', age = 0)
self.name = name
self.age = age
end
end


Person.new('Ivan', 20)
Person.new('Ivan')

但是,如果你只想传递年龄,这个调用看起来会很丑陋,因为无论如何你都必须为 name 提供空白字符串:

Person.new('', 20)

为了避免这种情况,Ruby 世界中有一种惯用的方法:options 参数。

class Person
attr_accessor :name, :age

def initialize(options = {})
self.name = options[:name] || ''
self.age = options[:age] || 0
end
end

Person.new(name: 'Ivan', age: 20)
Person.new(age: 20)
Person.new(name: 'Ivan')

你可以先放一些必须的参数,把所有可选的参数都塞进options

编辑

It seems Ruby 2.0 将支持真正的命名参数。

def example(foo: 0, bar: 1, grill: "pork chops")
puts "foo is #{foo}, bar is #{bar}, and grill is #{grill}"
end

# Note that -foo is omitted and -grill precedes -bar
example(grill: "lamb kebab", bar: 3.14)

关于ruby-on-rails - Rails 可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9710303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com