krystah
krystah

Reputation: 3733

Different ways to create this String in Ruby?

Disclaimer: Yes, this is homework and yes, I have already solved it.

Task: Create the String "0 10 20 30 40 50 60 70 80 90 100" <- Note, no whitespace

Obviously not using direct assignment, but using tools such as loops, ranges, splitting and such. I already finished this using a 10-increment loop, and I am pretty sure there are way more intelligent ways to solve it and I am curious about the alternatives.

How would you build a String like this?

Upvotes: 2

Views: 89

Answers (5)

Kal
Kal

Reputation: 2664

Just to be different and not use #step:

(0..10).map{|x| x * 10}.join(' ')

Upvotes: 2

the Tin Man
the Tin Man

Reputation: 160551

Just to be contrary, here are some using times with map, with_object and inject:

10.times.map{ |i| "#{ 10 * (i + 1) }" }.join(' ') # => "10 20 30 40 50 60 70 80 90 100"
10.times.with_object([]) { |i, o| o << "#{ 10 * (i + 1) }" }.join(' ') # => "10 20 30 40 50 60 70 80 90 100"
10.times.inject([]) { |o, i| o << "#{ 10 * (i + 1) }" }.join(' ') # => "10 20 30 40 50 60 70 80 90 100"

Upvotes: 0

Stefan
Stefan

Reputation: 114138

Numeric#step would work, too (here with a Ruby 2.1 style hash argument)

0.step(by: 10).take(11).join(' ')
#=> "0 10 20 30 40 50 60 70 80 90 100"

Upvotes: 1

Dhanu Gurung
Dhanu Gurung

Reputation: 8840

Second version using Range#step:

(0..100).step(10).to_a.join(' ')
# "0 10 20 30 40 50 60 70 80 90 100"

Upvotes: 3

Arup Rakshit
Arup Rakshit

Reputation: 118261

Yes there is using Range#step and Array#*:

(0..100).step(10).to_a * " "
# => "0 10 20 30 40 50 60 70 80 90 100"

Upvotes: 3

Related Questions