IT

Ruby로 명시 적으로 리턴하는 것이 좋은 스타일입니까?

lottoking 2020. 6. 12. 08:36
반응형

Ruby로 명시 적으로 리턴하는 것이 좋은 스타일입니까?


스타일에 관해서는 항상 "올바른 방법"( "Pythonic"방식)이있는 파이썬 배경에서 나온 루비도 마찬가지입니다. 나는 나 자신의 스타일 지침을 사용하고 있지만 소스 코드를 공개하려고 생각하고 있으며 작성되지 않은 규칙을 준수하고 싶습니다.

return메소드 에 명시 적으로 입력하는 것이 "루비 방식" 입니까? 나는 그것이 있거나없는 것을 보았지만 그것을하는 올바른 방법이 있습니까? 그것을 할 적절한 시간 이 있습니까? 예를 들면 다음과 같습니다.

def some_func(arg1, arg2, etc)
  # Do some stuff...
  return value # <-- Is the 'return' needed here?
end

오래된 (그리고 "답변 된") 질문이지만 대답으로 2 센트를 던질 것입니다.

TL; DR-반드시 그럴 필요는 없지만 코드를 좀 더 명확하게 만들 수 있습니다.

명시적인 리턴을 사용하지 않는 것이 "루비 방식"일 수도 있지만, 익숙하지 않은 코드를 사용하거나이 루비의 기능에 익숙하지 않은 프로그래머에게는 혼동이됩니다.

다소 고안된 예이지만, 이와 같은 작은 기능을 가진 이미징은 전달 된 수에 1을 더하고이를 인스턴스 변수에 할당합니다.

def plus_one_to_y(x)
    @y = x + 1
end

이것은 값을 반환하는 함수입니까? 인스턴스 변수를 할당하고 할당 된 값을 반환하기 때문에 개발자가 의미하는 바를 말하기가 실제로 어렵습니다.

훨씬 나중에 다른 프로그래머 (아마도 루비가 마지막으로 실행 된 코드 라인을 기반으로 반환하는 방법에 익숙하지 않은)가 와서 로깅을 위해 인쇄 문을 넣고 싶다고 가정하면 함수는 다음과 같습니다.

def plus_one_to_y(x)
    @y = x + 1
    puts "In plus_one_to_y"
end

무엇이든 반환 값을 기대하면 함수가 중단 됩니다 . 반환 값을 기대하는 것이 없다면 괜찮습니다. 분명히 코드 체인보다 더 어딘가에, 이것을 호출하는 것이 반환 된 값을 기대하고 있다면, 기대했던 것을 다시 얻지 못하기 때문에 실패 할 것입니다.

실제 질문은 이것입니다. 실제로 반환 값을 기대하는 것이 있습니까? 이 문제가 발생 했습니까? 앞으로 무언가가 깨질까요? 누가 알아! 모든 통화에 대한 전체 코드 검토 만 알려줍니다.

따라서 적어도 모범 사례 접근 방식은 중요한 경우 무언가를 반환한다는 것을 명시 적으로 나타내거나 그렇지 않을 때는 아무것도 반환하지 않는 것입니다.

작은 데모 함수의 경우 값을 반환하기를 원한다고 가정하면 다음과 같이 작성됩니다.

def plus_one_to_y(x)
    @y = x + 1
    puts "In plus_one_to_y"
    return @y
end

그리고 그것은 어떤 프로그래머에게나 그것이 가치를 반환한다는 것을 분명히 알 수 있으며, 그것을 깨닫지 않고 깨뜨리기가 훨씬 더 어렵습니다.

또는 다음과 같이 작성하고 반환 진술을 생략 할 수 있습니다 ...

def plus_one_to_y(x)
    @y = x + 1
    puts "In plus_one_to_y"
    @y
end

그런데 왜 귀환이라는 단어를 남기지 않겠습니까? 왜 거기에 넣고 무슨 일이 일어나고 있는지 100 % 명확하게 만드십시오. 말 그대로 코드의 성능에 영향을 미치지 않습니다.


아닙니다. 좋은 Ruby 스타일은 일반적으로 초기 수익에 대해 명시 적 수익 만 사용합니다 . 루비는 코드 미니멀리즘 / 암시 적 마술에 큰 영향을 미칩니다.

즉, 명시적인 반품으로 물건을 더 명확하거나 읽기 쉽게 만들면 아무 것도 해치지 않습니다.


필자는 개인적으로 return키워드를 사용하여 기능적 메소드 , 즉 주로 반환 값 으로 실행되는 메소드주로 부작용으로 실행되는 절차 적 메소드 를 구분합니다. 따라서 반환 값이 중요한 메서드는 반환 값에 return주의를 끌기 위해 추가 키워드를 가져 옵니다.

나는 함수를 호출 할 때 동일한 구별을 사용한다 : 함수 적 메소드는 괄호를 얻지 만 절차 적 메소드는 그렇지 않다.

마지막으로 블록과의 구별도 사용합니다. 기능 블록은 중괄호, 절차 블록 (예 : "일을하는"블록)은 do/를 얻습니다 end.

그러나 블록, 중괄호 및 do/ end가 다른 우선 순위를 사용하여 표현을 명확하게하기 위해 명시적인 괄호를 추가하는 대신 다른 스타일로 전환합니다. 매개 변수 목록 주위에 괄호를 추가하면 코드를 더 읽기 쉽게 만들면 문제의 방법이 절차 적 인 경우에도 수행합니다.


실제로 중요한 것은 다음을 구별하는 것입니다.

  1. 함수-반환 값에 대해 실행 된 메소드
  2. 절차-부작용에 대해 실행되는 방법

루비는 이것들을 구별하는 기본 방법을 가지고 있지 않으므로 프로 시저를 작성하는 데 취약 side_effect()하고 다른 개발자 는 프로 시저 의 암시 적 반환 값을 남용하기로 결정합니다 (기본적으로 불순 함수로 처리).

To resolve this, take a leaf out of Scala and Haskell's book and have your procedures explicitly return nil (aka Unit or () in other languages).

If you follow this, then using explicit return syntax or not just becomes a matter of personal style.

To further distinguish between functions and procedures:

  1. Copy Jörg W Mittag's nice idea of writing functional blocks with curly braces, and procedural blocks with do/end
  2. When you invoke procedures, use (), whereas when you invoke functions, don't

Note that Jörg W Mittag actually advocated the other way around - avoiding ()s for procedures - but that's not advisable because you want side effecting method invocations to be clearly distinguishable from variables, particularly when arity is 0. See the Scala style guide on method invocation for details.


The style guide states, that you shouldn't be using return on your last statement. You can still use it if it's not the last one. This is one of the conventions which the community follows strictly, and so should you if you plan to collaborate with anyone using Ruby.


That being said, the main argument for using explicit returns is that it's confusing for people coming from other languages.

  • Firstly, this is not entirely exclusive to Ruby. For example Perl has implicit returns too.
  • Secondly, the majority of the people that this applies to are coming from Algol languages. Most of those are way "lower level" than Ruby, hence you have to write more code to get something done.

A common heuristic for method length (excluding getters/setters) in java is one screen. In that case, you might not be seeing the method definition and/or have already forgotten about where you were returning from.

On the other hand, in Ruby it is best to stick to methods less than 10 lines long. Given that, one would wonder why he has to write ~10% more statements, when they are clearly implied.


Since Ruby doesn't have void methods and everything is that much more concise, you are just adding overhead for none of the benefits if you go with explicit returns.


I agree with Ben Hughes and disagree with Tim Holt, because the question mentions the definitive way Python does it and asks if Ruby has a similar standard.

It does.

This is such a well-known feature of the language that anyone expected to debug a problem in ruby should reasonably be expected to know about it.


It's a matter of which style you prefer for the most part. You do have to use the keyword return if you want to return from somewhere in the middle of a method.


Like Ben said. The fact that 'the return value of a ruby method is the return value of the last statement in the function body' causes the return keyword to be rarely used in most ruby methods.

def some_func_which_returns_a_list( x, y, z)
  return nil if failed_some_early_check


  # function code 

  @list     # returns the list
end

참고URL : https://stackoverflow.com/questions/1023146/is-it-good-style-to-explicitly-return-in-ruby

반응형