Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The 'upto' method in Ruby

Tags:

ruby

I'm learning Ruby, and there has been a bit of talk about the upto method in the book from which I am learning. I'm confused. What exactly does it do?

Example:

grades = [88,99,73,56,87,64]
sum = 0
0.upto(grades.length - 1) do |loop_index|
    sum += grades[loop_index]
end
average = sum/grades.length
puts average
like image 400
Billjk Avatar asked Mar 15 '12 20:03

Billjk


People also ask

How do you find the length of an integer in Ruby?

The size() function in Ruby returns the number of bytes in the machine representation of int.

What is integer in Ruby?

In Ruby, Integer class is the basis for the two concrete classes that hold whole numbers. These concrete classes are Bignum and Fixnum. Fixnum holds integer values that are shown in the native machine word, whereas Bignum holds the integer value outside the range of Fixnum.

What number is Ruby?

You can create one by writing it: 123 is Ruby code and it represents the number one-hundred-twenty-three. Negative numbers are created by prepending a minus - : This is the number minus-ninety-nine: -99 . And of course there are decimal numbers, too.


2 Answers

My example would have been this:

1.upto(5)  { |i| puts "Countup: #{i}" }

So what you're actually doing here is saying, I want to count up from 1 to the number 5, that's specifically what this part is saying:

1.upto(5)

The latter part of code (a block) is just outputting the iteration of going through the count from 1 up to 5. This is the output you might expect to see:

    Countup: 1
    Countup: 2
    Countup: 3
    Countup: 4
    Countup: 5

Note: This can be written is another way if you're using multilines:

1.upto(5) do |i|
puts "Countup: #{i}"
end

Hope this helps.

like image 58
Chris Pettitt Avatar answered Nov 21 '22 16:11

Chris Pettitt


From http://www.ruby-doc.org/docs/ProgrammingRuby/html/ref_c_integer.html#upto:

upto int.upto( anInteger ) {| i | block }

Iterates block, passing in integer values from int up to and including anInteger.

5.upto(10) { |i| print i, " " }

produces:

5 6 7 8 9 10
like image 31
Oliver Charlesworth Avatar answered Nov 21 '22 16:11

Oliver Charlesworth