your programing

끝에 "then"이있는 "if"문의 차이점은 무엇입니까?

lovepro 2020. 12. 30. 19:51
반응형

끝에 "then"이있는 "if"문의 차이점은 무엇입니까?


ifthen끝에 a 넣을 때이 두 Ruby 문의 차이점은 무엇입니까 if?

if(val == "hi") then
  something.meth("hello")
else
  something.meth("right")
end

if(val == "hi")
  something.meth("hello")
else
  something.meth("right")
end

then Ruby가 표현식의 조건과 실제 부분을 식별하는 데 도움이되는 구분 기호입니다.

if조건 then참 부분 else거짓 부분end

then한 줄로 식 을 작성 하지 않으려면 선택 사항 if입니다. 여러 줄에 걸친 if-else-end의 경우 개행은 조건부와 실제 부분을 분리하는 구분 기호 역할을합니다.

# can't use newline as delimiter, need keywords
puts if (val == 1) then '1' else 'Not 1' end

# can use newline as delimiter
puts if (val == 1)
  '1'
else
  'Not 1'
end

귀하의 질문과 직접적으로 관련이없는 간단한 팁이 있습니다. Ruby에는 if진술 같은 것이 없습니다 . 사실, 루비, 어떤 진술이없는 전혀은 . 모든 것이 표현입니다. if표현 찍은 분기에 평가 된 마지막 식의 값을 반환합니다.

따라서 쓸 필요가 없습니다.

if condition
  foo(something)
else
  foo(something_else)
end

이것은 다음과 같이 작성하는 것이 좋습니다.

foo(
  if condition
    something
  else
    something_else
  end
)

또는 한 줄로

foo(if condition then something else something_else end)

귀하의 예에서 :

something.meth(if val == 'hi' then 'hello' else 'right' end)

참고 : Ruby에는 삼항 연산자 ( condition ? then_branch : else_branch)도 있지만 완전히 불필요하므로 피해야합니다. C와 같은 언어에서 삼항 연산자가 필요한 유일한 이유는 C if에서 명령문이므로 값을 반환 할 수 없기 때문입니다 . 삼항 연산자는 표현식이고 조건부에서 값을 반환하는 유일한 방법이기 때문에 필요합니다. 하지만 Ruby에서는 if이미 표현식이므로 삼항 연산자가 필요하지 않습니다.


then당신이 쓰고 싶은 경우에만 필요 if한 줄에 표현 :

if val == "hi" then something.meth("hello")
else something.meth("right")
end

귀하의 예에서 대괄호는 중요하지 않으므로 두 경우 모두 건너 뛸 수 있습니다.

자세한 내용은 곡괭이 책 을 참조하십시오.


전혀 차이가 없습니다.

그리고 참고로 코드를 다음과 같이 최적화 할 수 있습니다.

something.meth( val == 'hi' ? 'hello' : 'right' )

The only time that I like to use then on a multi-line if/else (yes, I know it's not required) is when there are multiple conditions for the if, like so:

if some_thing? ||
  (some_other_thing? && this_thing_too?) ||
  or_even_this_thing_right_here?
then
  some_record.do_something_awesome!
end

I find it to be much more readable than either of these (completely valid) options:

if some_thing? || (some_other_thing? && this_thing_too?) || or_even_this_thing_right_here?
  some_record.do_something_awesome!
end

# or

if some_thing? ||
  (some_other_thing? && this_thing_too?) ||
  or_even_this_thing_right_here?
  some_record.do_something_awesome!
end

Because it provides a visual delineation between the condition(s) of the if and the block to execute if the condition(s) evaluates to true.

ReferenceURL : https://stackoverflow.com/questions/3083636/what-is-the-difference-between-if-statements-with-then-at-the-end

반응형