rubysymbolsruby-2.1

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?


Solution

  • 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

    As your example is taken out of context and contains errors, I've taken a liberty to make a more complete example.

    data    = []
    strings = ["Hello", "Bye", "Hello", "Hi"]
    
    strings.each do |string|
      hash = data.find{ |h| h[:label] == string }
      if hash.nil?
        data << {label: string, value: 1}
      else 
        hash[:value] += 1
      end
    end