Ruby奇数个哈希错误的参数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ruby奇数个哈希错误的参数相关的知识,希望对你有一定的参考价值。
case look
when 'side'
hash1 = {
'num' => 5,
'style' => 'sideStyle',
}
when 'front'
hash1 = {
'num' => 8,
'style' => 'frontStyle',
}
when 'back'
hash1 = {
'num' => 4,
'style' => 'backStyle',
'special' => 'yes',
}
else
hash1 = {
'num' => 2,
'style' => 'noStyle',
}
end
myStyle = Hash[hash1]
我的代码看起来像这样。
当我运行这段代码时,我得到“哈希的奇数参数”。
这是从哈希的正确方法吗?有人可以请帮助我如何解决它。
答案
连续的哈希初始化太多了。只需将case
的结果赋值为:
my_style =
case look
when 'side'
{
'num' => 5,
'style' => 'sideStyle',
}
when 'front'
{
'num' => 8,
'style' => 'frontStyle',
}
when 'back'
{
'num' => 4,
'style' => 'backStyle',
'special' => 'yes',
}
else
{
'num' => 2,
'style' => 'noStyle',
}
end
为了干,我个人最好这样做:
result =
case look
when 'side' then [5, "sideStyle"]
when 'front' then [8, "frontStyle"]
when 'back' then [4, "backStyle", "yes"]
else [2, "noStyle"]
end
result.zip(%w|num style special|).map(&:rotate).to_h
以上是关于Ruby奇数个哈希错误的参数的主要内容,如果未能解决你的问题,请参考以下文章