Error comparing Array in IF

Asked

Viewed 31 times

0

This is my code

v3 = []
w=j=k=0
puts "Digite o tamanho do vetor 1"
m = gets.to_i
v1 = Array.new(m)
puts "Digite o tamanho do vetor 2"
n = gets.to_i
v2 = Array.new(m)

for i in 0..m-1
    puts "Digite os valores do vetor 1: "
    v1.push(gets.to_i)
end
for i in 0..n-1
    puts "Digite os valores do vetor 2: "
    v2.push(gets.to_i)
end

while w <= m+n-1
    if (v1[j] < v2[k])
        v3.push(v1[j])
        j += 1
    elsif (v1[j] = v2[k])
        v3.push(v1[j])
        j = j +1
        k = k +1
    else
        v3.push(v2[k])
        k = k +1
    end
    w+=1
end

but he misses when I compare v1[j] < v2[k]

Error returned:

:20:in `<main>': undefined method `<' for nil:NilClass (NoMethodError)

1 answer

1

The way you’re creating arrays

Array.new(5)

it returns an array with 5 positions with values nil.

[nil, nil, nil, nil, nil]

Just create the v1, v2 arrays by just assigning [] the variables v1, v2

v1 = []
v2 = []

Browser other questions tagged

You are not signed in. Login or sign up in order to post.