verdure
verdure

Reputation: 3341

Error while running .each loop in ruby

I am trying to implement server side validations, to do that i receive the form values in the variable @value

    @value =  {"prev_school":{"name":"","class":"Nursery"},"sibling": {"name":""}}

    @validate = {"prev_school":[{"name":["is_mandatory","is_alphabets"]}}

In @variable I have defined the methods that need to be called for each field. My question is when I run the following code

     @value.each do |key,val| 
         @validate.each do |k,v|
            if k == key puts v end 
        end     
    end

I am getting an error pointing to the if statement

  syntax error, unexpected tIDENTIFIER, expecting kDO or '{' or '('

Could somebody please help with this.

Cheers! :)

Upvotes: 0

Views: 924

Answers (2)

WarHog
WarHog

Reputation: 8710

And you have to define hash either trough { "key" => "value" } syntax, or with { key: value } - in Ruby 1.9. So you variables should look like this:

@value =
{
  "prev_school" => {"name" => "", "class" => "Nursery"},
  "sibling" => {"name" => ""}
}
@validate = {"prev_school" => [{"name" => ["is_mandatory","is_alphabets"]}]}

In @validate you miss ] between two final }.

Upvotes: 1

mu is too short
mu is too short

Reputation: 434665

You want one of these:

@value.each do |key,val| 
  @validate.each do |k,v|
    if k == key
      puts v
    end 
  end     
end

or

@value.each do |key,val| 
  @validate.each do |k,v|
    puts v if k == key
  end     
end

Your version is a syntax error because Ruby doesn't know that you mean to end the if between key and puts so it is trying to interpret key puts v as an argument for == but gets confused.

Upvotes: 2

Related Questions