Program Tip

Ruby에서 세미콜론을 사용할 수 있습니까?

programtip 2020. 10. 29. 19:14
반응형

Ruby에서 세미콜론을 사용할 수 있습니까?


Ruby를 배울 때 모든 예제에 세미콜론이 없다는 것을 알았습니다. 각 진술이 자체 행에있는 한 이것이 완벽하게 괜찮다는 것을 알고 있습니다. 하지만 제가 궁금한 것은 Ruby에서 세미콜론을 사용할 있습니까?


예.

루비는 여러 문장을 한 줄에 묶고 싶지 않다면, 명령을 구분하기 위해 어떤 문자도 사용할 필요가 없습니다. 이 경우 세미콜론 (;)이 구분 기호로 사용됩니다.

출처 : http://articles.sitepoint.com/article/learn-ruby-on-rails/2


참고로 (j) irb 세션에서 세미콜론을 사용하여 엄청나게 긴 표현식 값을 인쇄하지 않도록하는 것이 유용합니다.

irb[0]> x = (1..1000000000).to_a
[printout out the whole array]

vs

irb[0]> x = (1..100000000).to_a; nil

특히 MyBigORMObject.find_all 호출에 좋습니다.


세미콜론 : 예.

irb(main):018:0> x = 1; c = 0
=> 0
irb(main):019:0> x
=> 1
irb(main):020:0> c
=> 0

한 줄짜리 루프에서 세미콜론으로 구분 된 여러 명령을 실행할 수도 있습니다.

irb(main):021:0> (c += x; x += 1) while x < 10
=> nil
irb(main):022:0> x
=> 10
irb(main):023:0> c
=> 45

세미콜론이 유용하다는 것을 알게 된 유일한 상황은 attr_reader에 대한 별칭 메서드를 선언 할 때입니다.

다음 코드를 고려하십시오.

attr_reader :property1_enabled
attr_reader :property2_enabled
attr_reader :property3_enabled

alias_method :property1_enabled?, :property1_enabled
alias_method :property2_enabled?, :property2_enabled
alias_method :property3_enabled?, :property3_enabled

세미콜론을 사용하면이를 3 줄로 줄일 수 있습니다.

attr_reader :property1_enabled; alias_method :property1_enabled?, :property1_enabled
attr_reader :property2_enabled; alias_method :property2_enabled?, :property2_enabled
attr_reader :property3_enabled; alias_method :property3_enabled?, :property3_enabled

나에게 이것은 가독성에서 실제로 벗어나지 않습니다.


예, 세미콜론은 Ruby에서 문 구분 기호로 사용할 수 있습니다.

내 전형적인 스타일 (그리고 내가 본 대부분의 코드)은 각 줄에 한 줄의 코드를 넣지 만 사용 ;은 꽤 불필요합니다.


다음 예에서와 같이 세미콜론을 사용하여 블록 구문을 유지하는 것이 흥미로울 수 있습니다.

a = [2, 3 , 1, 2, 3].reduce(Hash.new(0)) { |h, num| h[num] += 1; h }

한 줄의 코드를 유지합니다.

참고 URL : https://stackoverflow.com/questions/3953846/can-you-use-semicolons-in-ruby

반응형