user2936338
user2936338

Reputation: 11

Need to extract only the names from an array of hashes using Ruby

I have an output as follows:

[#<table1 employeename: "abc">, #<table1 employeename: "bbb">, #<table1 employeename: "ccc">, #<table1 employeename: "ddd">, #<table1 employeename: "eee">]

I would like to retrieve only the employee names in the following format using Ruby, please help as I am very new to Ruby?

('aaa', 'bbb', 'ccc', 'ddd', 'eee')

Upvotes: 1

Views: 47

Answers (2)

Patrick Oscity
Patrick Oscity

Reputation: 54684

If you are riding the Rails, you can use the pluck method to accomplish this

Employee.pluck(:name)
#=> ["Ashley", "John", "Peter", "Julie"]

which is equivalent to

Employee.all.map(&:name)

Upvotes: 1

Bharat soni
Bharat soni

Reputation: 2786

Another one you can queried data with selected attributes like

@data = Data.all.select("name")

Upvotes: 0

Related Questions