Jerome
Jerome

Reputation: 6189

Executing a calculation on an array of symbols

Working with and array of symbols

> I18n.available_locales
[:en, :it, :fr, :de]
> I18n.locale
:en

running an array calculation

> I18n.available_locales - I18n.locale

returns the error:

TypeError (no implicit conversion of Symbol into Array)

one cannot operate on the component to calculate with to transform it into an array

> I18n.locale.to_a
NoMethodError (undefined method `to_a' for :en:Symbol)

So what is the way to execute the calculation if the end-intent is to

<% I18n.inactive_locales.each do |locale| %>
   <li><%= link_to locale.to_s, { locale: locale } %></li>
<% end %>

Upvotes: 2

Views: 118

Answers (3)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

Make the second operand an array too, like this (for example):

I18n.available_locales - [I18n.locale]

So what is the way to execute the calculation if the end-intent is to

I'd probably do it inline (this way you can avoid patching I18n)

<% I18n.available_locales.each do |locale| %>
   <% next if locale == I18n.locale %>
   <li><%= link_to locale.to_s, { locale: locale } %></li>
<% end %>

Upvotes: 8

demir
demir

Reputation: 4709

In such cases, you can use Array() method

Array(I18n.locale)
#=> [:en]

Array([I18n.locale])
#=> [:en]

Array(nil)
#=> []

I18n.available_locales - Array(I18n.locale)
#=> [:it, :fr, :de]

Reference: https://ruby-doc.org/core-2.6/Array.html

Upvotes: 0

Horacio
Horacio

Reputation: 2965

It's because operator - needs an array

try

2.2.10 :003 > [:a,:b,:c] - [:a]
 => [:b, :c]

In your case would be something like

I18n.available_locales - [I18n.locale]

Upvotes: 0

Related Questions