【问题标题】:if statement inside an array creation ruby数组创建红宝石中的 if 语句
【发布时间】:2018-09-24 19:22:46
【问题描述】:

我正在尝试在数组创建中执行 if 语句

markers_index = Array.new        
@events.each_with_index do |event, index|
...

        markers_index << {
          type: 'Feature',
          geometry: {
            type: 'Point',
            coordinates: [event.longitude, event.latitude]
          },
          properties: {
            markerurl: event.photo.marker.url,
            divclass: marker_class,
            if has_popup
              popupContent: marker_popup
            end
          }
        }
    end

但它会引发语法错误

意外的':',期待keyword_end 弹出内容:'marker_popup'

这是一个错字还是我根本无法做到这一点,需要重复整个事情,把它包装在一个 if else 包装我的 marker_index 变量?尽量保持干燥..

【问题讨论】:

    标签: ruby-on-rails ruby dry


    【解决方案1】:

    例如:

    h= {
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: [event.longitude, event.latitude]
      },
      properties: {
        markerurl: event.photo.marker.url,
        divclass: marker_class,
      }
    }
    if has_popup
      h[:properties][:popupContent]= marker_popup
    end
    markers_index << h
    

    【讨论】:

    • 这很快,谢谢!关于数组的任何阅读建议?
    【解决方案2】:
    h= {
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: [event.longitude, event.latitude]
      },
      properties: {
        markerurl: event.photo.marker.url,
        divclass: marker_class,
      }.tap { |g| g[:popupContent] = marker_popup if has_popup }
    }
    

    Object#tap

    【讨论】:

    • 或者g.merge!(popupContent: marker_popup),如果你想保留哈希语法。
    【解决方案3】:

    除了像其他人提到的那样在创建哈希之后执行 if 条件之外,您还可以仅在语句评估为 true 时填充哈希 Key/Val 对的值。然后,您只需测试该值是否为 nil 以便稍后使用三元运算符(条件?如果为真:如果为假)对其采取行动/不采取行动:

    markers_index = Array.new        
    @events.each_with_index do |event, index|
    ...
    
            markers_index << {
              type: 'Feature',
              geometry: {
                type: 'Point',
                coordinates: [event.longitude, event.latitude]
              },
              properties: {
                markerurl: event.photo.marker.url,
                divclass: marker_class,
                popupContent: has_popup ? marker_popup : nil
              }
            }
        end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多