kingweaver88
kingweaver88

Reputation: 67

Ruby stop and move to next iteration of for loop

I have a for loop with an if elsif statement inside. On the first if, if the condition is met I want it to stop there and go on to the next iteration of the loop.

This is a very simplified version of what I am trying to do:

array = [1,2,3,4,"x"]
for i in 0..(array.count -1)
    if array[i] == "x"
        #start next for loop iteration without executing the elsif
    elsif array[i] < 3
        puts "YAY!"
    end
end

What I am exactly trying to do is iterating through an array which all but one of the elements are integers but one of them is a string. On the string element, I need the loop (whatever kind is best) to skip the rest of the code and go to the next iteration of the loop. This is important because the second if statement uses an 'array_element < 11 condition' so if it runs that on the string element I get "comparison of String with 11 failed"

so I would want arr[x][3] this is what i tried but it gives me 8 8 8 8 instead of a single 8.

arr = [[1,2,3,"4"], [5,6,7,8], [9,10,11,12]] 

    arr.each{|x| 
    x.each {|i| 
        next if x[3].instance_of? String 
        if x[3] < 12 puts x[3] 
        end 
} 
}

Ok this works!! Thank you iAmRubuuu!!

arr = [1,2,3,"4"], [5,6,7,8], [9,10,11,12], [13,14,15,"16"], [17,18,19,20]]

arr.each_with_index{|x, i| 

    next if x.last.instance_of? String

    if x.last < 21
    puts x.last
    end
}

give me the output

8
12
20

Upvotes: 1

Views: 7133

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118271

As per your edit, hope the below one you are looking for:

arr = [1, 2, 3, "11", 11]
arr.each do |x|
  next if x.instance_of? String
  puts "#{x} is #{x.class}"
end

Output:

1 is Fixnum
2 is Fixnum
3 is Fixnum
11 is Fixnum

EDIT

Code:

arr = [[1,2,3,"4"], [4,5,6,7], [8,9,10,11]] 

arr.each{|x|
x.each{ |i|
next if i.instance_of? String
puts "#{i} is #{i.class}"
}
}

Output:

1 is Fixnum
2 is Fixnum
3 is Fixnum
4 is Fixnum
5 is Fixnum
6 is Fixnum
7 is Fixnum
8 is Fixnum
9 is Fixnum
10 is Fixnum
11 is Fixnum

V_1(from your first comment in my answer post)

arr = [[1,2,3,"4"], [4,5,6,7], [8,9,10,11]] 
puts arr[1].last,arr.last.last

Output:

7
11

V_2(from your first comment in my answer post)

arr = [[1,2,3,"4"], [4,5,6,7], [8,9,10,11]] 
arr.each_with_index{ |x,i|
next if i == 0
#p x,i
p "last element of inner array:#{x.last}"
}

Output:

"last element of inner array:7"
"last element of inner array:11"

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230386

Don't use for in, use each.

(0..10).each do |i|
  next if i == 5

  if i == 10
    puts "YAY!"
  end
end

Upvotes: 5

Related Questions