【问题标题】:How to escape a dash "-" in a Ruby symbol?如何在 Ruby 符号中转义破折号“-”?
【发布时间】:2012-01-18 21:38:50
【问题描述】:

我正在使用带有 Ruby On Rails 的 jquery-mobile。

我想创建一个按钮链接,这意味着data-role="button" 出现在生成的 HTML 中。

我试过了:

<%= link_to "Play", game_play_path, :data-role => "button" %>

然后,我得到一个错误

undefined local variable or method `role' for #<#<Class:0x007fdc25668ee8>:0x007fdc25658610>

有没有办法使用:xxx 表示法来转义破折号,还是我应该只使用"xxx" 表示法?

(我同意这是一个表面问题,但我希望我的代码保持一致并且不喜欢异常)

【问题讨论】:

    标签: ruby ruby-on-rails-3 jquery-mobile


    【解决方案1】:

    在符号名称前后使用单引号,并带有冒号前缀:

    :'data-role' => 'button'
    

    这里有一个很好的符号参考:

    http://www.troubleshooters.com/codecorn/ruby/symbols.htm#_What_do_symbols_look_like

    Ruby 1.9之后你也可以这样做

    'data-role': 'button'
    

    【讨论】:

    【解决方案2】:

    如果您发现语法 &lt;%= link_to "Play", game_play_path, :"data-role" =&gt; "button" %&gt; 丑陋,因为它使用旧的哈希语法,另一种涉及使用 ruby​​ 1.9 哈希语法的方法是执行以下操作:

    <%= link_to "Play", game_play_path, data: {role: "button"} %>
    

    哈希叠印在 html 输出中生成数据和角色之间的连字符。

    请谨慎,因为这仅适用于 data-something 属性,但在您的情况下,它是一个更令人赏心悦目的选择。

    另外,如果你有更多的 data-something 属性,你也可以将它们写在嵌套哈希中:

    <%= link_to "Play", game_play_path, data: {role: "button", other1: "value1", other2: "value2"} %>
    

    【讨论】:

      【解决方案3】:
      <%= link_to "Play", game_play_path, :"data-role" => "button" %>
      

      【讨论】:

      • 或者使用直字符串"data-role"。不需要它是一个符号。 #codegolf
      【解决方案4】:

      用单引号括起来:

      :'data-role' => "button"
      

      【讨论】:

        猜你喜欢
        • 2011-01-18
        • 1970-01-01
        • 2010-09-15
        • 1970-01-01
        • 2011-12-17
        • 1970-01-01
        • 2011-01-09
        • 2016-05-30
        相关资源
        最近更新 更多