CR7
CR7

Reputation: 710

fetch value of two columns into a single hash variable

In Ruby on Rails, I am trying to fetch value from user_id and id column in rails. Now I am using the following code which concatenate two columns firstname and lastname

@profiles = Profile.all.map{|p| "#{p.users_firstname} #{p.users_lastname}"}

Instead I have to add the columns as two entries. Please help. Thanks in advance

Update

I want to get the values like this

@profile = ['user1_firstname', 'user1_lastname','user2_firstname', 'user2_lastname',....]

Upvotes: 1

Views: 937

Answers (4)

Jay-Ar Polidario
Jay-Ar Polidario

Reputation: 6603

Your current code will yield something like:

@profiles = [ 'Edie Pineo', 'Tierra Cardiel', 'Sparkle Berrey' ]

You're asking:

Instead I have to add the columns as two entries

So, if I get it correctly you want instead something like:

@profiles = [ ['Edie', 'Pineo'], ['Tierra', 'Cardiel'], ['Sparkle', 'Berrey'] ]

... which is an Array of Array of Strings as opposed to your current code which is an Array of Strings.

If this is so, the following is a solution:

@profiles = Profile.all.map{|p| [p.users_firstname, p.users_lastname] }

Update 1 (unique values):

@profiles = Profile.pluck(:users_firstname, :users_lastname).uniq

Update 2 (unique values + disregard trailing and leading whitespaces):

@profiles = Profile.pluck(:users_firstname, :users_lastname).map{|array| array.map(&:strip) }.uniq

Update 3 (unique values + disregard strict equality for String & Integer)

# if you want string values
@profiles = Profile.pluck(:users_firstname, :users_lastname).map{|array| array.map(&:to_s) }.uniq

# if you want integer values
@profiles = Profile.pluck(:users_firstname, :users_lastname).map{|array| array.map(&:to_i) }.uniq

Update 4 (1-level array as opposed to nested arrays)

...continuing from our discussion and to answer your Update question

@profiles = Profile.pluck(:users_firstname, :users_lastname).flatten

- tested working

Upvotes: 1

margo
margo

Reputation: 2927

I think you want to use pluck. Below will return an array of arrays with each nested array containing the firstname and the lastname.

Profile.pluck(:users_firstname, :users_lastname)

If, as the title of your question reads, you want a hash, you can convert it to a hash with to_h. It's not clear from your question how you want the hash to be formatted

Upvotes: 1

Ho Man
Ho Man

Reputation: 2345

Assuming users_firstname and users_lastname are attributes of Profile, you can skip map altogether:

Profile.all.pluck(:user_firstname, :users_lastname)

Upvotes: 1

Sajin
Sajin

Reputation: 1638

Is this what you are looking for?

@profiles = Profile.all.select(:users_firstname, :users_lastname).to_a

Upvotes: 0

Related Questions