简体   繁体   中英

How to remove a string from an array with Ruby 2.5.3?

I develop on Ruby on Rails 5.2. With the purpose of managing translations, I wish to allow the user to select a language which is different from his current language. The list of configured languages of the application is

 all_languages = I18n.config.available_locales

all_languages is an Array. puts all_languages returns:

en fr de it

The user language is defined in the users table. A method returns current user's language

user_language = current_user.language

user_language is a String. puts user_language returns:

en

I try to apply the delete(obj) method to the array, but this does not alter the array:

all_languages.delete(user_language)

I try to work on arrays only, still it does not alter the languages array:

remove_language = Array.new
remove_language << user_language

puts remove_language returns:

en

puts all_languages - remove_language returns:

en fr de it

where the en language should be removed. I don't understand why it remains in the list!

I18n.config.available_locales returns symbols *. And your current_user.language is a string. "en" is not at all the same thing as :en . That said, this should work:

all_languages = I18n.config.available_locales.dup # copy the array
all_languages.delete(:en)
# or, for your case
all_languages.delete(current_user.language.to_sym)


# non-mutating way
all_langs_without_en = I18n.config.available_locales.reject { |loc| loc == :en }

* at least in rails 4.2, where I checked this.

Try this

all_languages = ["en","fr","de","it"]
user_language = "en"
all_languages.delete_at(all_languages.index(user_language))

#=> ["fr","de","it"]

Your code doesn't work, because available_locales returns an array of symbols and you are attempting to remove a string .

a = [:en, :fr, :de, :it]
a.delete('en')
#=> nil

a #=> [:en, :fr, :de, :it]

To fix this, you have to turn your string into a symbol. Furthermore, you should avoid delete because it modifies the receiver (modifying available_locales might result in bugs later on). You can use Rails' Array#without instead which returns a new array:

all_languages = I18n.config.available_locales
#=> [:en, :fr, :de, :it]

user_language = current_user.language.to_sym
#=> :en

all_languages.without(user_language)
#=> [:fr, :de, :it]

This solution should meet your need:

l = I18n.config.available_locales
l.pop
I18n.config.available_locales = l

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM