Mario R.
Mario R.

Reputation: 31

Why does this Ruby for loop fail?

Ok, so I just want to do this Java in Ruby:

int [] nums = { 2,4,6,8,10 };
for ( int i = 0; i < nums.length; i++ ){
    nums[i]=nums[i]+100;
}

I am doing this:

nums = Array[2,4,6,8,10];
hello = nums.length;
for i in 0..hello 
    # puts i
    nums[i]=nums[i] + 100
end

Code fails with:

qq.rb:5:in `block in <main>': undefined method `+' for nil:NilClass (NoMethodError)
        from qq.rb:3:in `each'
        from qq.rb:3:in `<main>'

WHY?

Thanks in advance for your help.

Upvotes: 1

Views: 65

Answers (1)

user229044
user229044

Reputation: 239240

You're looping past the end of the array.

.. is inclusive. 0..3 produces the numbers 0, 1, 2, 3.

You want ... which does not include the last value in the range. 0...3 produces 0, 1, 2.

That said, what you really want is some idiomatic Ruby:

nums = [2,4,6,8,10]
nums.map! { |x| x + 100 } # => [102, 104, 106, 108, 110]

Upvotes: 6

Related Questions