【问题标题】:Building a hash or array in a helper method in rails 4在 rails 4 的辅助方法中构建哈希或数组
【发布时间】:2015-05-27 23:05:52
【问题描述】:

我正在尝试使用辅助方法构建一个哈希数组(我认为这就是我的表述方式),以便我可以在我的视图中使用它。我从@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'],

【问题讨论】:

  • 你想要一个简单的数组。哈希数组看起来 [{time_start: '10:00am', time_end: '10:15am'},{time_start: '1:00pm', time_end: '2:15pm'}]
  • 您的示例输出不是哈希数组,而是数组数组。不过,您基本上已经明白了……您遇到了什么问题?
  • 它甚至不是一个数组数组——它是三个数组,它们之间有逗号。如果它是一个数组数组,它​​将被括在另一对方括号中。

标签: ruby-on-rails arrays ruby-on-rails-4 hash helper


【解决方案1】:

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

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
  • 帮助方法返回一个数组数组,而不是哈希数组。它是一个二维数组(“宽度”为 2,长度为 x 其中0 ≤ x &lt; +infinity)。
  • helper 方法返回包含 DateTime 对象的数组数组,而不是 String。您可以轻松地操作 DateTime 对象,以便按照您想要的方式对其进行格式化。 “为什么不直接将 DateTime 转换为格式良好的字符串?”你会问,我会回答“因为你可以在最后一刻在视图中这样做,也许有一天你会想要在渲染之前在 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

【讨论】:

  • 这个“taken_times(@your_events).each”是指这个“taken_times(@other_events).each”还是我要创建@your_events?无法让它在视图中工作并尝试调试。
  • 我已经使用变量@your_events 向您展示了将此变量替换为您的变量,该变量表示您想要获取开始和结束时间的事件。如果在您的视图中您想获取@other_events 的时间,那么可以将此变量传递给taken_times 方法。
【解决方案2】:

您要求的是一个哈希数组([{}、{}、{}、...]):

  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

【讨论】:

    猜你喜欢
    • 2016-07-22
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多