【问题标题】:Need to refactor to the new Ruby 1.9 hash syntax [duplicate]需要重构为新的 Ruby 1.9 哈希语法 [重复]
【发布时间】:2017-10-15 18:26:39
【问题描述】:

我有一个配方,其中包含以下代码,但未通过 lint 测试:

service 'apache' do
  supports :status => true, :restart => true, :reload => true
end

它失败并出现错误:

Use the new Ruby 1.9 hash syntax.
  supports :status => true, :restart => true, :reload => true

不确定新语法是什么样的...有人可以帮忙吗?

【问题讨论】:

    标签: ruby chef-recipe rubocop


    【解决方案1】:
    service 'apache' do
      supports status: true, restart: true, reload: true
    end
    

    当您有符号作为键时,您可以使用这种新语法。

    【讨论】:

      【解决方案2】:

      在 Ruby 版本 1.9 中引入了一种新的哈希文字语法,其键是符号。哈希使用“哈希火箭”运算符来分离键和值:

      a_hash = { :a_key => 'a_value' }
      

      在 Ruby 1.9 中这种语法是有效的,但是只要键是一个符号,它也可以写成:

      a_hash = { a_key: 'a_value' }
      

      正如 Ruby 样式指南所说,当您的哈希键是符号 (see) 时,您应该更喜欢使用 Ruby 1.9 哈希文字语法:

      # bad
      hash = { :one => 1, :two => 2, :three => 3 }
      
      # good
      hash = { one: 1, two: 2, three: 3 }
      

      另外提示:不要将 Ruby 1.9 哈希语法与哈希火箭混合在同一个哈希文字中。当你有不是符号的键时,请坚持哈希火箭语法(see)

      # bad
      { a: 1, 'b' => 2 }
      
      # good
      { :a => 1, 'b' => 2 }
      

      所以你可以试试:

      service 'apache' do
        supports status: true, restart: true, reload: true
      end
      

      如果您想查看 Rubocop 的“方式”是什么,您可以在命令行中运行它,这将仅针对 HashSyntax 警告或标志自动更正您的代码:

      rubocop --only HashSyntax --auto-correct
      

      【讨论】:

      • 我如何输入带有 2 个符号的哈希,例如:{:key => :value, :key2 => :value2} ?
      • 只要{ key: :value, key2: :value2 },hash key和hash value都是符号。
      猜你喜欢
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多