首页 > 解决方案 > Ruby - 没有将 false 隐式转换为字符串

问题描述

我在下面解释的代码中收到以下错误。“没有将 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-railsruby

解决方案


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

a << b ? c : d << e

b你的在哪里!search.nil?)评估为

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

虽然您希望它会评估为

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

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


推荐阅读