Ask Your Question
5

How can I iterate over a hash?

asked 2012-11-14 16:20:12 -0500

jhl gravatar image

updated 2013-01-03 14:24:40 -0500

llowder gravatar image

I'm modifying a module's defined type to accept a hash as a parameter. The keys and values of this hash are arbitrary strings that need to be formatted and passed to as arguments to an exec. Is there a way to iterate over the key/value pairs without writing a custom function? If not, what advice do you have for writing the custom function?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
7

answered 2012-11-18 17:50:43 -0500

glarizza gravatar image

updated 2012-11-18 17:54:34 -0500

It sounds like you're wanting to pass a series of arguments and their values in a hash like this:

exec_arguments = { 'certname' => 'test.example.com',
                   'server'   => 'puppet.example.com',
                   'report'   => 'true',
                 }

and get a result like:

--certname test.example.com --server puppet.example.com --report true

I don't believe there's anything like this in stdlib, but it sounds like simple reduction of a hash to a string, which could be done like this in Ruby:

exec_arguments.reduce('') do |final_string, hash_value|
  final_string << "--#{hash_value.first} #{hash_value.last}"
end

I would create a function called "reduce_arguments" that would return this string ... (more)

edit flag offensive delete link more
2

answered 2012-11-21 17:38:52 -0500

jhl gravatar image

The use case @glarizza outlines is essentially what I'm trying to do. I ended up adding a join_keys_to_values function to stdlib. This function takes a hash and separator and returns an array of keys joined with the separator to their values. For example, joinkeysto_values({'foo'=>1, 'bar'=>2}, ' = ') returns ['foo = 1', 'bar = 2']. So, you could do something like:

$exec_arguments = { 'certname' => 'test.example.com',
                    'server'   => 'puppet.example.com',
                    'report'   => 'true',
                  }

$argument_string = '--' + join(join_keys_to_values($exec_arguments, ' '), ' --')

which would result in the string:

'--certname test.example.com --server puppet.example.com --report true'
edit flag offensive delete link more

Comments

Thanks, jhl! It was handy to find this function recently in stdlib; it proved useful in converting a hash to a set of 'export KEY=value' statements that could be ...(more)

AronR gravatar imageAronR ( 2014-01-23 15:53:55 -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

4 followers

Stats

Asked: 2012-11-14 16:20:12 -0500

Seen: 2,380 times

Last updated: Nov 21 '12