ruby - Why do you need to subtract from size of array? -
ruby - Why do you need to subtract from size of array? -
when seek run sec line without subtracting size of array, won't work. why not?
values = [10, 9, 11, 2, 45] max_element = values.size - 1 first = values[0] in 0..max_element while first < values[i] first = values[i] end end p "the largest value #{first}"
besides methods on enumerable
or array
such each
, for
iterator loops on collection of elements?
because array indices zero-based, in c or java:
values = [10, 9, 11, 2, 45] values.size #=> 5 values[0] #=> 10 (1st element) values[4] #=> 45 (last element) values[5] #=> nil (this beyond lastly item)
you can utilize ...
(three dots) exclude range's end:
for in 0...values.size # ... end
furthermore, while
should if
:
if first < values[i] first = values[i] end # or first = values[i] if first < values[i]
ruby loops for-loop
Comments
Post a Comment