Philip7899
Philip7899

Reputation: 4677

can't access value using .each with ruby

Here is my code:

<% @user.errors.each do |key, value| %>
   <% puts 'key is' + key.to_s + 'value is ' + value.to_s %>
   <% if key == 'email' %>
      <% puts 'key is def email' %>
   <% else %>
      <% puts 'key is def not email' %>
   <% end %>
<% end %>

This outputs:

key isemailvalue is can't be blank
key is def not email
key ispassword_confirmationvalue is doesn't match Password
key is def not email
key isprofile_namevalue is This is not valid.
key is def not email

The problem is that it is saying "key is def not email" even when they key definitely is "email" How do I fix this? Thanks

Upvotes: 0

Views: 87

Answers (1)

Holger Just
Holger Just

Reputation: 55758

In Ruby, there is a difference between Strings and Symbols. Both of these types do not compare as equals (although they often look kind of similar). In your case, the key is probably a Symbol, not a String.

You should thus either compare to a symbol or first "transform" the symbol to a string.

key = :email
key == 'email'
# => false

key.to_s == 'email'
# => true

key == :email
# => true

Upvotes: 3

Related Questions