Viraj Parimi Viraj Parimi - 22 days ago 6
Ruby Question

updating array based on symbols Ruby

How does one update the array based on symbols? Like

data = []
string = "Hello"
if( !data.include? string )
count += 1
data.insert(-1, {
label: string,
value: count,
})
else
#logic to change count value if string is encountered again
end


I was thinking of finding the index where the string lies and then delete that to insert another updated values at that index. Is this the right approach?

Answer

Just use find to get the match, provided its the only one in the array. You can use select to get multiple matches. After that just update the count

I've also updated your hash creation to make it neater.

data = []
string = "Hello"
if( !data.include? string )
   count += 1
   data << {label: string, value: count}
else
  data.find{|h| h[:label] == string}[:count] += 1
end
Comments