Forum: Ruby Ruby Array -> String Conversion Issue

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7863582496e914f1ffce56f98d468f72?d=identicon&s=25 Nathan O. (Guest)
on 2006-03-06 17:56
(Newbie Alert!)

I have a CGI script that takes an address and tries to put it as hidden
form data on a new page. "post" is a hash of POST data.

["addr1", "addr2", "city", "state", "zip", "country"].each do |part|
	puts "<input type=\"hidden\" name=\"" + part.to_s + "\" value=\"" +
post[part.to_s] + "\" />"
end

This code generates the complaint that "part" is an array, and thus
cannot be converted to a string. How do I iterate over each item in that
array of address data?
9358cc96c46055cd68d4a76a9aefe026?d=identicon&s=25 Daniel Harple (Guest)
on 2006-03-06 18:28
(Received via mailing list)
On Mar 6, 2006, at 5:57 PM, Nathan O. wrote:

> This code generates the complaint that "part" is an array, and thus
> cannot be converted to a string. How do I iterate over each item in
> that
> array of address data?

I see no problem with that code, except I would write it as:

%w{addr1 addr2 city state zip country}.each do |part|
   puts %{<input type="hidden" name="#{part}" value="#{post[part]}" />}
end

You don't have another local variable named part, do you?

When you convert an array to a string, all the elements just get
mashed together: %w{foo bar baz}.to_s -> "foobarbaz"

-- Daniel
7863582496e914f1ffce56f98d468f72?d=identicon&s=25 Nathan O. (Guest)
on 2006-03-07 01:44
Ah, my mistake. I assumed it was talking about my "part" variable when
it was talking about my reference to post[part.to_s], which returns an
array. I'm not sure it's the tidiest fix, but I changed this to
post[part.to_s].to_s, and it works. Well, that part works, now I have
other issues :-)

> %w{addr1 addr2 city state zip country}.each do |part|
>    puts %{<input type="hidden" name="#{part}" value="#{post[part]}" />}
> end

This looks like one of those things I'm going to have to look up! Thanks
for the pointer!
This topic is locked and can not be replied to.