Martin
Martin

Reputation: 11336

Generate a specific array in ruby

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

Answers (2)

Kyle
Kyle

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).ma­p{ |i| [i, i.to_­s] unles­s i.zer­o? }.com­pact

Upvotes: 8

doesterr
doesterr

Reputation: 3965

((-5..-1).to_a + (1..5).to_a).map { |i| [i, i.to_s] }

Upvotes: 1

Related Questions