【发布时间】:2018-01-01 10:28:02
【问题描述】:
我目前正在学习 ruby,但我无法让我的嵌入式 ruby 正常工作,我们将不胜感激。
我基本上是想在我的嵌入式 ruby 中编写这个 if 语句的简短版本
<% entity.attributes.each do |key, value| %>
<%= if key == "name"
link_to @entity, edit_entity_path(entity)
else
value
end %>
<%= end %>
根据我的理解(和这个post)应该可以这样写
<% entity.attributes.each do |key, value| %>
<%= key == "name" ? link_to @entity, edit_entity_path(entity) : value %>
<%= end %>
这似乎不起作用。我做错了什么?
Ralils 错误消息: 语法错误,意外 tIVAR,期待 keyword_do 或 '{' 或 '(' ...ey == "name") ? ...
提前感谢您的帮助
【问题讨论】:
-
在 Ruby 中使用三元运算符时,您的
if : else必须每个都用括号括起来,或者如果在其中传递函数,它们需要使用function(args)形式而不是空格(@ 除外987654326@ 等)。例如true ? true.is_a? TrueClass : false会引发错误,但true ? true.is_a?(TrueClass) : false不会。如果您使用三元运算符返回,您可以像assertion ? (return something) : (return something_else)
标签: ruby-on-rails if-statement embedded-ruby