在 rails 4 的辅助方法中构建散列或数组

Building a hash or array in a helper method in rails 4

我正在尝试使用辅助方法构建一个哈希数组(我认为这就是我的措辞方式),以便我可以在我的视图中使用它。我从 @other_events.time_start 和 @other_events.time_end 列中获取 2 个值。

helper.rb

 def taken_times()
     @taken_times = []
    @other_events.each do |e|
    @taken_times << { e.time_start.strftime("%l:%M %P") => e.time_end.strftime("%l:%M %P")}
    end
    @taken_times
 end

我想要的是这样的哈希数组:

['10:00am', '10:15am'],
['1:00pm', '2:15pm'],
['5:00pm', '5:15pm'],

本质上是
['e.time_start', 'e.time_end'],

我认为你应该将你的方法重构为:

def taken_times(other_events)
  other_events.map { |event| [event.time_start, event.time_end] }
end
  • 辅助方法不再设置全局变量 @taken_times 但您可以轻松调用 @taken_times = taken_times(other_events).
  • 辅助方法正在使用它的参数 other_events 而不是在全局变量 @other_events 上,在某些视图中可能是 nil
  • 辅助方法returns 一个数组数组,而不是一个散列数组。它是一个二维数组("width" of 2,x 的长度,其中 0 ≤ x < +infinity)。
  • 辅助方法 returns 包含 DateTime 对象而非字符串的数组数组。您可以轻松地操作 DateTime 对象,以便按照您想要的方式对其进行格式化。 "Why not directly transform the DateTime into nice-formatted strings?" 你会问,我会回答“因为你可以在视图中做到这一点,在最后一刻,也许有一天你会想要在 time_starttime_end 在渲染之前。

那么在你看来:

taken_times(@your_events).each do |taken_time|
  "starts at: #{taken_time.first.strftime("%l:%M %P")}"
  "ends at: #{taken_time.last.strftime("%l:%M %P")}"
end

您正在请求一个哈希数组([{}、{}、{}、...]):

  Array: []
  Hash: {}

但是您期望的是数组 ([[], [], [] ...])

你应该这样做:

def taken_times()
    @taken_times = []
    @other_events.each do |e|
    @taken_times << [e.time_start.strftime("%l:%M %P"), e.time_end.strftime("%l:%M %P")]
    end
    @taken_times
end