Ask Your Question

How to replace .each in Ruby 1.9?

asked 2014-04-09 03:47:02 -0600

rcit gravatar image

I'm new to Puppet and Ruby and got the following problem ->

While using Ruby 1.8, i can successfully use the following code in my templates:

<% @privatetcpports.each do |privtcpport| -%>
$<%=iptablescommand -%> -A INPUT -p tcp --dport <%=privtcpport -%> -j LOG -m limit --limit 6/minute
$<%=iptablescommand -%> -A INPUT -p tcp --dport <%=privtcpport -%> -j DROP

The content of privatetcpports is filled via a Hiera-lookup in my init.pp and can consist of 0 to n ports. Problem is, when i update to Ruby 1.9, i get:

undefined method `each' for "":String

When i change .each to .each_line, as suggested ... (more)

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2014-04-09 07:59:50 -0600

ffrank gravatar image

updated 2014-04-10 04:24:21 -0600

I have honestly no idea of how Ruby 1.9 figures into this, but I suspect that in the "0 ports" case, puppet helpfully replaces the variable value [] with "" and implicitly converts to String. Ouch.

You can use this idiom to make "everything" an array:

<% [ @privatetcpports ].flatten.each do |port| -%>

Note that this still does the wrong thing if indeed [] now gets spuriosly translated to [ "" ]. You'd need to filter out empty entries then

<% [ @privatetcpports ].reject { |x| x.empty? }.flatten.each do |port -%>

Even if this does the trick, it's pretty ugly. You should definitely try and find out ... (more)

edit flag offensive delete link more



String#each was removed in ruby 1.9 the alternative is string.splt(/\n/).each This is a gotcha when moving from puppet on redhat (shipping with ruby 1.8 ...(more)

jonuwz gravatar imagejonuwz ( 2014-04-10 17:37:41 -0600 )edit

answered 2014-04-10 02:36:40 -0600

rcit gravatar image

No, Puppet did the right thing. Thanks to your help i was able to find my problem. I recently added a new hierarchy level to Hiera and made the mistake of using "" instead of [] in there. Now that this is fixed, the original code also works under the newer Ruby version. Doh!

Thank you! :)

edit flag offensive delete link more

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


Asked: 2014-04-09 03:47:02 -0600

Seen: 297 times

Last updated: Apr 10 '14