我想用以下签名定义一个方法:
name
是必需的。all_day
是可选的。start_time
是必需的。end_time
为all_day
。true
即location
是可选的,并且是一个类似于:
location = {name => "Chelsea Piers", address => "10th Avenue", city => "New York"}
需要location[:name]
,其他键是可选的。
这是我的代码:
class Event
def initialize(name, all_day=false, start_time, end_time, **location)
@name = name
@all_day = all_day
@start_time = Time.parse(start_time)
@end_time = Time.parse(end_time)
@location = location
end
end
如何实施要求d。如果all_day
为true
且我没有location
,则该参数的以下代码中的语法是:
Event.new(name, true, start_time, location)
正确?我可以像这样创建一个新的Event
对象:
Event.new(name, false, start_time, end_time)
答案 0 :(得分:4)
旁注:
location = {name => "Chelsea Piers",
address => "10th Avenue",
city => "New York"}
不是有效的ruby对象。它可能是:
location = {name: "Chelsea Piers",
address: "10th Avenue",
city: "New York"}
或:
location = {:name => "Chelsea Piers",
:address => "10th Avenue",
:city => "New York"}
Sidenote#2:
存在XY问题:您实际上根本不需要all_day
参数。它可以从是否设置end_time
得出。
最后,命名参数和双splat参数location
可能会混合在一起。总结:
class Event
def initialize(name, start_time, end_time = nil, location_name:, **location)
@name = name
@all_day = !end_time.nil?
@start_time = Time.parse(start_time)
@end_time = Time.parse(end_time) if end_time
@location = location.merge(name: location_name)
end
end