0

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

2
  • Do not use + to build string. Do not use puts in ERb.Y ou can write it in more readable way by this: key is <%= key %>, value is <%= value %>. Commented Jan 6, 2014 at 8:36
  • You don't know that key is "email"; you only know that key.to_s returned "email". When adding debugging to an erb, use <%=d key %>. d is a helper function that inspects the value. That way you'll find out what key really is. Commented Jan 21, 2014 at 15:13

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.