3

What is the shortest way to create this array in Ruby:

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Thanks for any help!

2
  • 2
    It depends on your intention. Do you want to start with 10 and skip by 10 until 100, or do you want to divide between 10 and 100 evenly with 10, etc? Commented Aug 5, 2013 at 13:30
  • 1
    What have you written? What did searches for this reveal? Commented Aug 5, 2013 at 14:24

3 Answers 3

13

What about Range#step:

(10..100).step(10).to_a
#=> [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Or Numeric#step:

10.step(100, 10).to_a
#=> [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Sign up to request clarification or add additional context in comments.

2 Comments

You second one is nice one to know... for me... :) Now I stopped thinking about any alternative solutions..
#2 is what I was going to recommend.
8

You can use Range and call Enumerable#map method on it, like this:

(1..10).map{|i| i * 10}
# => [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Or, as suggested by @JörgWMittag, with Object#method method that returns Method instance which is converted to proc by & notation:

(1..10).map(&10.method(:*))
# => [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Comments

2

This builds an array directly from the constructor.

Array.new(10){|i| (i + 1) * 10}
# => [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

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.