I’m encountering an issue while trying to check if a string is present in an array within my Rails application. The include? method seems to be giving unexpected results.
I have an array named @categories which holds a list of strings like ["poverty", "hunger"]. I’m trying to use this array to pre-select checkboxes in a form based on whether the values where selected last time.
In this code, I print the values @categories, @categories&.include?(un_kind[1]), and un_kind[1], which give me the following respective values:["poverty", "hunger"] false poverty
<%= @categories %>
<% Array(t("#{cat_l}.enums.un_kind").invert).each do |un_kind| %>
<%= @categories&.include?(un_kind[1]) %>
<%= un_kind[1] %>
<div class="form-check">
<%= check_box_tag "un_kind[]", un_kind[1], @categories&.include?(un_kind[1]), class: 'form-check-input' %>
<%= label_tag "un_kind_#{un_kind[1]}", un_kind[0], class: 'form-check-label' %>
</div>
<% end %>
>Solution :
The problem here is a string vs symbol issue. You’re getting your un_kind[1] from your i18n locale lookup, which means it will be :poverty NOT "poverty". Therefore:
> ["poverty", "hunger"].include? :poverty
false
…as opposed to:
> ["poverty", "hunger"].include? "poverty"
true
The confusing part here is that when you print a symbol it’s automatically converted to its string form. This is why generally for debugging it’s better to use inspect on the objects that you’re printing, that will usually give you better visibility as to what’s going on.
I’m sure you’re way ahead of me, the simple fix is to .to_s your un_kind[1] object: @categories&.include?(un_kind[1].to_s)