参数的可选性取决于其他参数

时间:2017-08-05 23:38:05

标签: ruby

我想用以下签名定义一个方法:

  • 一个。 name是必需的。
  • all_day是可选的。
  • ℃。 start_time是必需的。
  • d。除非end_timeall_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_daytrue且我没有location,则该参数的以下代码中的语法是:

Event.new(name, true, start_time, location)

正确?我可以像这样创建一个新的Event对象:

Event.new(name, false, start_time, end_time)

1 个答案:

答案 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