需要重构新的Ruby 1.9哈希语法
发布时间:2020-12-17 03:07:46 所属栏目:百科 来源:网络整理
导读:参见英文答案 Hash syntax in Ruby ????????????????????????????????????1个 我有一个配方,其中包含以下代码,即lint测试失败: service 'apache' do supports :status = true,:restart = true,:reload = trueend 它失败并出现错误: Use the new Ruby 1.9 h
参见英文答案 >
Hash syntax in Ruby ????????????????????????????????????1个
我有一个配方,其中包含以下代码,即lint测试失败: service 'apache' do supports :status => true,:restart => true,:reload => true end 它失败并出现错误: Use the new Ruby 1.9 hash syntax. supports :status => true,:reload => true 不确定新语法是什么样的……有人可以帮忙吗? 解决方法
在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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |