我创建了一个包含许多键的散列,并且我想省略具有nil
值的键:
h = {
:key0 => val0,
:key1 => val1, # I want to include this key only if val1 is not nil
:key2 => val2
}
除了
if val1
h = {
:key0 => val0,
:key1 => val1,
:key2 => val2
}
else
h = {
:key0 => val0,
:key2 => val2
}
end
类似的东西
h = {
:key0 => val0,
:key1 => val1 if val1, # gives an error
:key2 => val2
}
编辑:感谢到目前为止的回复,真的很有用。有没有一种方法可以定义哈希文字而无需事后处理?