数组创建中的 if 语句 ruby
if statement inside an array creation ruby
我正在尝试在数组创建中执行 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 变量中?试图保持干燥..
例如:
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
除了像其他人提到的那样在哈希创建之后执行 if 条件之外,您还可以仅在语句计算结果为真时填充哈希 Key/Val 对的值。然后,您只需测试该值是否为零,以便 act/not 稍后使用三元运算符对其进行操作(条件?如果为真:如果为假):
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
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。
我正在尝试在数组创建中执行 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 变量中?试图保持干燥..
例如:
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
除了像其他人提到的那样在哈希创建之后执行 if 条件之外,您还可以仅在语句计算结果为真时填充哈希 Key/Val 对的值。然后,您只需测试该值是否为零,以便 act/not 稍后使用三元运算符对其进行操作(条件?如果为真:如果为假):
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
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。