Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to either set a variable to 0 or, if it is already set, increment by 1

Tags:

arrays

ruby

I know of the ||= operator, but don't think it'll help me here...trying to create an array that counts the number of "types" among an array of objects.

array.each do |c|
  newarray[c.type] = newarray[c.type] ? newarray[c.type]+1 ? 0
end

Is there a more graceful way to do this?

like image 202
dancow Avatar asked Sep 02 '09 18:09

dancow


People also ask

How do you increment a variable in ruby?

It turns out that the author of Ruby, matz suggests the official way to increment and decrement variables in ruby is by using the += and -= operators.

Is set ordered in Ruby?

keys . Because the Ruby 1.9 Set library happens to be built upon a Hash currently, you can currently use Set as an ordered set.

How to increment value by 1 in JavaScript?

JavaScript has an even more succinct syntax to increment a number by 1. The increment operator ( ++ ) increments its operand by 1 ; that is, it adds 1 to the existing value. There's a corresponding decrement operator ( -- ) that decrements a variable's value by 1 . That is, it subtracts 1 from the value.

Does ++ exist in Ruby?

Ruby has no pre/post increment/decrement operator. For instance, x++ or x-- will fail to parse. More importantly, ++x or --x will do nothing! In fact, they behave as multiple unary prefix operators: -x == ---x == -----x == ......


1 Answers

types = Hash.new(-1) # It feels like this should be 0, but to be
                     # equivalent to your example it needs to be -1
array.each do |c|
  types[c.type] += 1
end
like image 178
sepp2k Avatar answered Oct 03 '22 18:10

sepp2k