d3bug3r
d3bug3r

Reputation: 2586

Ruby on Rails convert list to array

the following query return as follow:

@cref = Creference.all
@cref = @cref.group_by{|cc| cc["name"]}

result: Object {US: Array[1], UK: Array[1]}

And these query return the result as:

@countries = Product.joins(:user).distinct.where("state is not null and country <> ''").where(:users => {:merchant_status => 1}).pluck(:country)
@countries.map! {|country| country.split.map(&:capitalize).join(' ')}
@countries = @countries.uniq

result: ["US", "UK"]

I am using gon to pass the result to the country drop down list:

gon.search_location_list = @countries +  @cref

How can I make the first result format to match the second one? Thanks!!!

Upvotes: 1

Views: 1535

Answers (3)

Awais Shafqat
Awais Shafqat

Reputation: 546

In short you question is that you want to concatenate array values with hash keys. So for this the simplest solution is

@cref = @cref.group_by{|cc| cc["name"]}.keys

This would return the keys in array format and than you can concatenate. But that would result is same value but you can call uniq() on it.

Upvotes: 0

shivam
shivam

Reputation: 16506

How can I make the first result format to match the second one?

In your first example you are using group_by which returns a Hash. In second example you are using map which returns an Array. Use the same thing both places to get similar format.

@cref = @cref.map{|cc| cc["name"]}
# ["US", "UK"]

Upvotes: 1

Matt C
Matt C

Reputation: 4555

After your first two lines, add this line:

@cref = @cref.values

Upvotes: 0

Related Questions