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
The size() function in Ruby returns the number of bytes in the machine representation of int.
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.
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.
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.
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 fromint
up to and includinganInteger
.5.upto(10) { |i| print i, " " }
produces:
5 6 7 8 9 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With