Reputation: 11336
Is there a way to easily generate this array in Ruby?
[[-5,'-5'],[-4,'-4'],[-3,'-3'],[-2,'-2'],[-1,'-1'],[1,'1'],[2,'2'],[3,'3'],[4,'4'],[5,'5']]
Basically, it contains 10 elements from -5 to 5 with an integer key and string value.
Upvotes: 1
Views: 104
Reputation: 22258
(-5..5).map{ |i| [i, i.to_s] }
doester pointed out that the spec does not include 0
, any of these would work:
(-5..5).reject{ |i| i == 0 }.map{ |i| [i, i.to_s] }
(-5..5).reject(&:zero?).map{ |i| [i, i.to_s] }
(-5..5).map{ |i| [i, i.to_s] unless i == 0 }.compact
(-5..5).map{ |i| [i, i.to_s] unless i.zero? }.compact
Upvotes: 8