我仍然是Puppet的初学者。所以,请忍受我。假设我通过某个模块在Puppet中创建了此哈希
@media screen and (max-width: 480px) {
.tile-post > :first-child
{
position:relative;
}
}
如何找到哈希中特定键和值对的键?在这种情况下,例如,我想查找account = {
user@desktop1 => {
owner => john,
type => ssh-rsa,
public => SomePublicKey
},
user@desktop2 => {
owner => mary,
type => ssh-rsa,
public => SomePublicKey
},
user@desktop3 => {
owner => john,
type => ssh-rsa,
public => SomePublicKey
},
user@desktop4 => {
owner => matt,
type => ssh-rsa,
public => SomePublicKey
}
}
拥有的所有密钥。因此,预期结果将类似于:
john
预先感谢
答案 0 :(得分:2)
https://ruby-doc.org/core-2.5.1/Hash.html#method-i-select
account.select {|key, value| value['owner'] == 'john'}.keys
答案 1 :(得分:2)
该问题询问如何在Puppet中执行此操作,但令人困惑的是,哈希是Ruby哈希,并且该问题还具有Ruby标签。
无论如何,这是您在Puppet中执行的操作:
$account = {
'user@desktop1' => {
'owner' => 'john',
'type' => 'ssh-rsa',
'public' => 'SomePublicKey',
},
'user@desktop2' => {
'owner' => 'mary',
'type' => 'ssh-rsa',
'public' => 'SomePublicKey',
},
'user@desktop3' => {
'owner' => 'john',
'type' => 'ssh-rsa',
'public' => 'SomePublicKey',
},
'user@desktop4' => {
'owner' => 'matt',
'type' => 'ssh-rsa',
'public' => 'SomePublicKey',
}
}
$users = $account.filter |$k, $v| { $v['owner'] == 'john' }.keys
notice($users)
应用人偶导致:
Notice: Scope(Class[main]): [user@desktop1, user@desktop3]
答案 2 :(得分:1)
使用Enumerable#each_with_object
的另一个选项:
account.each_with_object([]) { |(k, v), a| a << k if v['owner'] == 'john'}
#=> ["user@desktop1", "user@desktop3"]
将键和值设置为String
。