Click to See Complete Forum and Search --> : Ruby Hash Key Comparison Error


nko
03-02-2006, 05:41 PM
I've got a CGI script written in Ruby. I'm trying to iterate through
my POST data and do one thing if a given key has the word "line" in it
and another if it doesn't. Here's my code so far:

post.each {|x, y|
if x.to_s =~ "line"
puts ""
else
puts "<input type=\"hidden\" name=\"" + x.to_s + "\" value=\"" +
y.to_s + "\" />"
end
}

Running this script from the browser and filling in some dummy POST
data at the command line, it complains about that second line (the
=~):

shippingForm.rb:63:in `=~': type mismatch: String given (TypeError)
from shippingForm.rb:63
from shippingForm.rb:62:in `each'
from shippingForm.rb:62

Since I'm comparing a string to a string, I'm at a complete loss. Any ideas?

truls
03-03-2006, 01:22 AM
I'm just guessing here, but since the =~ operator seems to be the regexp operator in Ruby as well as Perl, shouldn't the code read:

if x.to_s =~ /line/

At least in Perl all regexp expressions are written as /expression/.

nko
03-03-2006, 05:20 PM
I figured that out a few minutes after posting my question, but I'd lieft the quotes around my string, so it looked like: /"line"/... which, of course, didn't work!

Much thanks. Now I've got a new question, so I'll start another thread :-)