programing

변수가 범위 내에 있는지 확인하는 중입니까?

javajsp 2023. 6. 23. 21:46

변수가 범위 내에 있는지 확인하는 중입니까?

다음과 같은 작업을 수행하는 루프를 작성해야 합니다.

if i (1..10)
  do thing 1
elsif i (11..20)
  do thing 2
elsif i (21..30)
  do thing 3
etc...

하지만 지금까지 구문적인 측면에서 잘못된 길을 걸어왔습니다.

if i. between? (1, 10)행동 1다른 사이라면? (11,20)행동 2...

사용===연산자(또는 동의어)include?)

if (1..10) === i

@Baldu가 말했듯이 === 연산자를 사용하거나 내부적으로 ===를 사용하는 경우 사용 사례/:

case i
when 1..10
  # do thing 1
when 11..20
  # do thing 2
when 21..30
  # do thing 3
etc...

그래도 범위를 사용하고 싶다면...

def foo(x)
 if (1..10).include?(x)
   puts "1 to 10"
 elsif (11..20).include?(x)
   puts "11 to 20"
 end
end

사용할 수 있습니다.
if (1..10).cover? i then thing_1 elsif (11..20).cover? i then thing_2

그리고 패스트 루비의 이 벤치마크에 따르면 더 빠릅니다.include?

일반적으로 다음과 같은 기능을 통해 훨씬 더 나은 성능을 얻을 수 있습니다.

if i >= 21
  # do thing 3
elsif i >= 11
  # do thing 2
elsif i >= 1
  # do thing 1

질문에 대한 직접적인 대답은 아니지만, "내부"와 반대의 경우:

(2..5).exclude?(7)

진실의

가장 빠른 방법이 필요한 경우 기존 비교 방법을 사용합니다.

require 'benchmark'

i = 5
puts Benchmark.measure { 10000000.times {(1..10).include?(i)} }
puts Benchmark.measure { 10000000.times {i.between?(1, 10)}   }
puts Benchmark.measure { 10000000.times {1 <= i && i <= 10}   }

시스템 인쇄에서:

0.959171   0.000728   0.959899 (  0.960447)
0.919812   0.001003   0.920815 (  0.921089)
0.340307   0.000000   0.340307 (  0.340358)

보다시피 이중 비교가 거의 3배 빠릅니다.#include?또는#between?방법!

Ruby에서 구축할 수 있는 보다 역동적인 답변:

def select_f_from(collection, point) 
  collection.each do |cutoff, f|
    if point <= cutoff
      return f
    end
  end
  return nil
end

def foo(x)
  collection = [ [ 0, nil ],
                 [ 10, lambda { puts "doing thing 1"} ],
                 [ 20, lambda { puts "doing thing 2"} ],
                 [ 30, lambda { puts "doing thing 3"} ],
                 [ 40, nil ] ]

  f = select_f_from(collection, x)
  f.call if f
end

그래서, 이 경우에, "범위"는 경계 조건을 잡기 위해 닐로 울타리를 치고 있습니다.

문자열:

(["GRACE", "WEEKLY", "DAILY5"]).include?("GRACE")

#=>참

언급URL : https://stackoverflow.com/questions/870507/determining-if-a-variable-is-within-range