Vivek Vivek - 4 months ago 11
Ruby Question

Ruby: which method to use for array of hashes to get a string with all hash values?

i have an array

[{name: "vivek"},{name:"ramesh"},{name: "suresh"},{name:"ganesh"}]


i want to create a method that return output as

"vivek,ramesh,suresh and ganesh".


if there are only two hashs like

[{name: "vivek"},{name: "ramesh"}]


output should be

"vivek and ramesh"


if names are more than 5 output should be "vivek, ramesh, suresh , nilash,ganesh etc .."

arr=[{name: 'vivek'},{name: 'Ganesh'},{name: 'Suresh'},{name: 'Ramesh'},{name: 'Bavesh'}]#,{name: 'Mukesh'}]
a = arr.size

case a

when 1
puts arr[0][:name]


when 2
puts arr[0][:name]+" and "+arr[1][:name]



when 3..5
ar = []
i=0
while i<arr.size-2
ar << arr[i]
i += 1
end

ar.each{|hash| printf "#{hash[:name]}"+","}

printf "#{arr[-2][:name]} and #{arr[-1][:name]}."

puts ""


when 6..100
ar = []
i=0
while i<4
ar << arr[i]
i += 1
end

ar.each{|hash| printf "#{hash[:name]}"+","}

printf "#{arr[4][:name]} etc..."

puts ""

else
puts "Error"
end


i did like this..but i know there should be a better way to do this with suitable methods can anybody help ..

Answer

I would do something like this:

def names_to_sentence(array)
  names = array.map { |hash| hash[:name] }

  case names.length
  when (0..1)
    names.first.to_s
  when (2..5)
    "#{names[0...-1].join(', ')} and #{names[-1]}"
  else
    "#{names[0..4].join(', ')} etc"
  end
end

names_to_sentence([{name: "vivek"},{name:"ramesh"},{name: "suresh"},{name:"nilash"},{name:"ganesh"},{name: "foobar"}])
#=> "vivek, ramesh, suresh, nilash, ganesh etc"
names_to_sentence([{name: "vivek"},{name:"ramesh"},{name: "suresh"},{name:"ganesh"}])
#=> "vivek, ramesh, suresh and ganesh"
names_to_sentence([{name: "vivek"},{name: "ramesh"}])
#=> "vivek and ramesh"
names_to_sentence([{name: "vivek"}])    
#=> "vivek"
names_to_sentence([])    
#=> ""
Comments