2

I need to put all the elements of a database column of an ActiveRecord model into an array. I do so like this:

code_array = []
Language.all.each do |lang|
  code_array<<lang.code
end

=> ["af", "sq", "ar", "hy", "az", "eu", "be", "bn", "bs", "bg", "ca", "ceb", "ny", "zh-CN", "zh-TW", "hr", "cs", "da", "nl", "en", "eo", "et", "tl", "fi", "fr", "gl", "ka", "de", "el", "gu", "ht", "ha", "iw", "hi", "hmn", "hu", "is", "ig", "id", "ga", "it", "ja", "jw", "kn", "kk", "km", "ko", "lo", "la", "lv", "lt", "mk", "mg", "ms", "ml", "mt", "mi", "mr", "mn", "my", "ne", "no", "fa", "pl", "pt", "ma", "ro", "ru", "sr", "st", "si", "sk", "sl", "so", "es", "su", "sw", "sv", "tg", "ta", "te", "th", "tr", "uk", "ur", "uz", "vi", "cy", "yi", "yo", "zu"]

But this must be possible with more elegant and/or less code?

1 Answer 1

6

The method you are looking for is pluck

Language.pluck(:code)

Incedentally, even if you don't use pluck, you could significantly improve your code by changing:

code_array = []
Language.all.each do |lang|
  code_array<<lang.code
end

to

Language.all.map(&:code)

Your code is iterating over all the results, taking the field code and pushing it onto an array, and then moving to the next element. It is often more efficient to map a function to a set or array.

Sign up to request clarification or add additional context in comments.

6 Comments

Your proposed improvement is purely aesthetic. Underlying operations are still the same. Meaning, it is not "more efficient".
Perfect answer! I never heard of the pluck method and it is what I was looking for when writing this question. I could have thought of map though. Somehow map is difficult to get into my active ehh repertoire.
@SergioTulentsev: Is there a more efficient way to do it? If not, I am very happy with this aesthetic improvement.
@Flip: yes, it's certainly nicer code than what you had. I was just pointing out a false claim.
@Flip: pluck is definitely the way to go. If Language has lots of other columns, you can select only the needed one. Something like: Language.select('code').map(&:code).
|

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.