루비에서 다른 범위를 생성 할 수 있습니다. 즉, 가능한 모든 /[0-9A-ZA-Z] {3} /

StackOverflow https://stackoverflow.com/questions/613697

  •  03-07-2019
  •  | 
  •  

문제

나는 루비를 사용하는 것 같은 느낌이 든다. /[0-9A-Za-z]{3}/

나는 사용할 수 없다 succ 왜냐하면 "999".succ => "1000" 그리고 "zZz".succ => "aaAa". 노조 할 수 없기 때문에 범위를 사용하는 데 어려움이 있습니다. (0..9), ('A'..'Z'), ('a'..'z')

그래서 나는 다음과 같이 썼다.

def alphaNumeric
  #range and succ don't cut it for [0-9a-zA-Z]
  (0..9).each{|x|yield x.to_s}
  ('a'..'z').each{|x|yield x}
  ('A'..'Z').each{|x|yield x}
end
def alphaNumericX3
  alphaNumeric{ |a|
    alphaNumeric{ |b|
      alphaNumeric{ |c|
        yield a+b+c
      }
    }
  }
end
alphaNumericX3.each{|x|p x}

내 질문은 2 배입니다.

덜 못생긴 방법이 있습니까? alphaNumericX3 매개 변수에서 정의 할 수 있습니다 (alphaNumeric, 3)?

추신 : 나는 범위에 대한 새로운 클래스를 정의 할 수 있다는 것을 알고 있습니다. 그러나 그것은 확실히 짧지 않습니다. 이 다음 블록을 위의 블록보다 짧고 명확하게 만들 수 있다면 다음을 수행하십시오.

class AlphaNum
  include Comparable
  attr :length
  def initialize(s)
    @a=s.chars.to_a
    @length=@a.length
  end
  def to_s
    @a.to_s
  end
  def <=>(other)
    @a.to_s <=> other.to_s
  end
  def succ
    def inc(x,n)
      return AlphaNum.new('0'*(@length+1)) if x<0
      case n[x]
      when '9'
        n[x]='A'
      when 'Z'
        n[x]='a'
      when 'z'
        n[x]='0'
        return inc(x-1,n)
      else
        n[x]=n[x].succ
      end
      return AlphaNum.new(n.to_s)
    end
    inc(@length-1,@a.clone)
  end
end
# (AlphaNum.new('000')..AlphaNum.new('zzz')).each{|x|p x}
#  === alphaNumericX3.each{|x|p x}
도움이 되었습니까?

해결책

사용 Array#product:

alpha_numerics = ('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a
alpha_numerics
  .product(alpha_numerics, alpha_numerics)
  .map { |triplet| triplet.join('') }

다른 팁

class String
  def nextify
    case self
    when '9' then 'A'
    when 'Z' then 'a'
    when 'z' then '0'
    else self.succ
    end
  end
end

class AlphaNum
  def initialize(string)
    @string = string
  end

  def succ
    @string.split(//).inject("") { |s,n| s << n.nextify }
  end

  def method_missing(*args, &block)
    @string.send(*args, &block)
  end
end

a = AlphaNum.new("999")
puts a.succ #=> 'AAA'
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top