【问题标题】:Ruby - No implicit conversion of false into StringRuby - 没有将 false 隐式转换为字符串
【发布时间】:2019-10-30 12:16:45
【问题描述】:

下面解释的代码出现以下错误。 “没有将 false 隐式转换为字符串”

  def search_form(target, search)
    raw("<span class='no_print'>" <<
            form_tag('/' + target + '/', :method => :get) <<
            text_field_tag(:search, search) <<
            submit_tag('Search', data: { disable_with: "Searching..." }) <<
            !search.nil? ? link_to('Clear', root_path, class: 'clearingLink') : "" <<
            '</form>' <<
            '</span>' <<
            form_focus('search'))
  end

!search.nil? ? link_to('Clear', root_path, class: 'clearingLink') : "" <<
This is the line I have added recently. Can anyone please let me know what is the wrong with this ?

【问题讨论】:

  • 你用ruby-on-rails标记了你的问题我想知道你为什么通过字符串连接构建HTML sn-p而不使用视图?
  • 嘿。此代码 sn-p 已添加到控制器本身中。我得到了这个项目的工作....

标签: ruby-on-rails ruby


【解决方案1】:

"str" &lt;&lt; false 是您遇到的错误的最小示例。该错误是与运算符优先级有关的误解的结果。值得注意的是,?: 的优先级低于&lt;&lt;;所以

a << b ? c : d << e

(其中b 是您的!search.nil?)评估为

(a << b) ? c : (d << e)

虽然你希望它评估为

a << (b ? c : d) << e

解决方案:添加括号以确保所需的评估顺序。

【讨论】:

  • 谢谢。有效。我以这种方式纠正了它。 (!search.nil? ? link_to('Clear', root_path, class: 'clearingLink') : "")
  • “解决方案:添加括号以确保所需的评估顺序。” – 就个人而言,我更喜欢以下解决方案:永远不要使用条件运算符。在 Ruby 中没有必要。 C语言中存在条件运算符,因为运算符是表达式,if是语句,所以如果要使用条件表达式,就需要条件运算符。但是在Ruby中,if是条件表达式,所以不需要条件运算符,完全没用。 Stack Overflow 上的大量涉及 Ruby 中条件运算符的问题被证明是优先级问题,...
  • ... 而条件表达式只是具有您期望的优先级:unless search.nil? then link_to('Clear', root_path, class: 'clearingLink') else "" &lt;&lt; '&lt;/form&gt;' &lt;&lt; '&lt;/span&gt;' &lt;&lt; form_focus('search')) end.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-06
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多