1

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.

4
  • What do you mean by simplify? Maybe it would be better if you showed how you were using the array. Commented Nov 9, 2012 at 1:32
  • Generate the array with call instead of declare each value. Commented Nov 9, 2012 at 1:33
  • Why do you want that array? It doesn't seem very useful. Commented Nov 9, 2012 at 12:40
  • To create a dropdown with those options using best_in_place gem. The integer value is what will be saved on the database. Commented Nov 9, 2012 at 17:36

2 Answers 2

8
(-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
Sign up to request clarification or add additional context in comments.

2 Comments

Either this answer, or the specification is wrong. The spec does not include an [0, "0"] element.
My favorite is the one with reject(&:zero?)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.