Daniel K Daniel K - 1 year ago 134
Ruby Question

Chef - join method separator not recognized in erb template file

New to Ruby, I'm trying to list system users (on one row, comma separated) in an erb file, with the following code:

<% IO.readlines("/etc/passwd").each do |pwd| %><% user = pwd.split(":").first %><% users = user.split.join(",") %><%= users %><% end %>

but it's not joining with comma, just pasting the strings from the array consecutively with no spaces. same result if I leave the (",") off the join.

Any idea what's going wrong, or a better way to do this?

Answer Source
<%= IO.readlines('/etc/passwd').reject {|l| l.start_with?('#')}.map {|l| l.split(':')[0]}.join(',') %>

which is hideously ugly, but works.

This line users = user.split.join(",") is trying to split user, which is a string that only has the username of the current iteration. And because you're writing the content of users (which is just user from that iteration) in each iteration, it just appended without a space. (joining a single string means the character never gets introduced.)

For code like this, especially since it does not require either Chef's environment nor an ERB, it's easier to see what it's doing by putting it in its own script file or running with irb and then adding puts lines to debug.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download