itsource

Ruby의 "continue"에 해당합니다.

mycopycode 2023. 7. 16. 13:20
반응형

Ruby의 "continue"에 해당합니다.

C와 많은 다른 언어들에는,continue루프 내부에서 사용될 때 루프의 다음 반복으로 이동하는 키워드입니다.이것과 동등한 것이 있습니까?continue루비의 키워드?

네, 라고 합니다.next.

for i in 0..5
   if i < 2
     next
   end
   puts "Value of local variable is #{i}"
end

그러면 다음이 출력됩니다.

Value of local variable is 2
Value of local variable is 3
Value of local variable is 4
Value of local variable is 5
 => 0..5 

next

또한, 을 보세요.redo현재 반복을 다시 수행합니다.

Ian Purton의 답변을 조금 더 관용적인 방법으로 작성합니다.

(1..5).each do |x|
  next if x < 2
  puts x
end

인쇄:

  2
  3
  4
  5

내부 루프 및 반복기 방법:each그리고.mapnext루비의 키워드는 루프의 다음 반복으로 점프하는 효과를 가질 것입니다.continue다)로

하지만 실제로는 현재 블록에서 되돌아오는 것뿐입니다.따라서 반복과 관련이 없는 경우에도 블럭을 사용하는 모든 방법에 사용할 수 있습니다.

Ruby에는 두 가지 다른 루프/반복 제어 키워드가 있습니다.redo그리고.retryRuby QuickTips에서 그들과 그들 사이의 차이점에 대해읽어보세요.

제 생각에 그것은 next라고 불립니다.

다음을 사용하면 해당 조건을 무시하고 나머지 코드가 작동합니다.아래에 전체 스크립트와 출력을 제공했습니다.

class TestBreak
  puts " Enter the nmber"
  no= gets.to_i
  for i in 1..no
    if(i==5)
      next
    else 
      puts i
    end
  end
end

obj=TestBreak.new()

출력: 숫자 10 입력

1 2 3 4 6 7 8 9 10

조건부로 다음을 사용할 수 있습니다.

before = 0
"0;1;2;3".split(";").each.with_index do |now, i|
    next if i < 1
    puts "before it was #{before}, now it is #{now}"
    before = now
end

출력:

before it was 0, now it is 1
before it was 1, now it is 2
before it was 2, now it is 3

언급URL : https://stackoverflow.com/questions/4010039/equivalent-of-continue-in-ruby

반응형