作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我有课
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/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!