Ask Your Question
0

Getting values from an array of hashes

asked 2017-12-13 11:13:02 -0500

gilbo gravatar image

Hello

I have an array of hashes like so:

[{networking_ip => XX.XX.XX.XX}, {networking_ip => XX.XX.XX.XX}]

What i'd like to do is just return the XX.XX.XX.X values into an array. Note: the array might be made up of more than 2 hashes, but they'll always take the form {networking_ip => XX.XX.XX.XX}

Thanks for reading! Rich

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2017-12-13 12:09:25 -0500

DarylW gravatar image

updated 2017-12-13 12:56:53 -0500

Looking at https://puppet.com/docs/puppet/5.3/la..., if you always have a hash that contains a key networking_ip and you want to pull out the value from that hash for that key, and map them into an array, you would use the built in map function.

Two different ways to solve this problem... if there will never be any keys in the hash other than networking_ip, then you could just pull out the value

$array_of_hashs = [{networking_ip => 1.2.3.4}, {networking_ip => 5.6.7.8}]
# using the '.map' function
$array_of_networking_ips = $array_of_hashes.map | $key, $value | {  $value }
# using the '.values' function from the stdlib at https://forge.puppet.com/puppetlabs/stdlib#values
$array_of_networking_ips_stdlib = $array_of_hashes.values
# $array_of_networking_ips should be [ '1.2.3.4', '5.6.7.8']

If you wish to access the value by the networking_ip key, you would do the following:

$array_of_hashs = [{networking_ip => 1.2.3.4}, {networking_ip => 5.6.7.8}]
$array_of_networking_ips = $array_of_hashes.map | $hash | {  $hash['networking_ip']  }
# $array_of_networking_ips should be [ '1.2.3.4', '5.6.7.8']
edit flag offensive delete link more

Comments

1

Thanks very much - I'd got as far as the first option but that doesn't work as the result after the .map is exactly the same hash as you start with, thus "values" doesn't work as it expects to be given a hash not an array. Option 2 though does exactly what i need - Thankyou!

gilbo gravatar imagegilbo ( 2017-12-13 14:28:58 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2017-12-13 11:13:02 -0500

Seen: 1,244 times

Last updated: Dec 13 '17