Beginner question: create array with block?

Simply put, I’m trying to generate a constant for displaying length
measurements in a select(). I would like to go from 1 to 40 but display
’ for feet. So the array I need is something like:

MEASUREMENTS = [[1, 1’], [2, 2’], [3, 3’]…]

Here is what I’ve got so far:

1.upto(40) {|x| [x.to_s + “’”, x]}

But I’m not sure how to create an array of arrays with that. Maybe
map()? Thanks!

m = []

1.upto(40) {|x| m << [x.to_s + “’”, x]}

cheers
ivor

That worked great. I was so close! Thank you.

Taylor S. wrote:

But I’m not sure how to create an array of arrays with that. Maybe
map()? Thanks!

Yup, you could use map (aka collect) as follows…

select_array = (1…40).collect { |x| [ “#{x}’”, x ] }

iterates through (1…40), appending the result of the block for that
element to an array that gets returned after the collect function
completes, and sets select_array equal to the ‘temporary’ array that the
collect method returns

Hope it helps!
Gustav P.
[email protected]


about me:
My greatest achievement was when all the other
kids just learnt to count from 1 to 10,
i was counting (0…9)

  • gustav.paul

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs