Anton Kan
Anton Kan

Reputation: 123

Just add new (different) elements to the array in Ruby (Rails)?

I want to create an array in Rails that contains every value of two columns but each just one time. So, for example, there is in column "A" {1,5,7,1,7} and in column "B" {3,2,3,1,4}.

When I just wanted an array with all elements of "A", I would write:

Model.uniq.pluck(:A)

And I would get {1,5,7}.

Is there an option in Rails to make the same thing with two columns, so just getting all values one time that are contained in two columns? (Here it would be {1,5,7,3,2,4})

Thanks for help!

Upvotes: 0

Views: 192

Answers (2)

Swati
Swati

Reputation: 862

records = []
Model.all.map {|e| records << [e.A, e.B] }
uniq_records = records.flatten.uniq

Hope this would help you.

Thanks

Upvotes: 0

Andrew Marshall
Andrew Marshall

Reputation: 96994

Yup, pass multiple column names to pluck:

Model.pluck(:A, :B)
#=> [[1, 3], [5, 2], [7, 3], [1, 1], [7, 4]]

But of course you want the values together and uniqued so:

Model.pluck(:A, :B).flatten.uniq
#=> [1, 3, 5, 2, 7, 4]

Doing Model.uniq.pluck(:A, :B).flatten won’t work since it will just get distinct rows (i.e. combinations of A & B), so you’d still have to uniq again after flattening.

Upvotes: 3

Related Questions