Rubyで異なる範囲を生成します。つまり、可能なすべての/ [0-9A-Za-z] {3} /

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

  •  03-07-2019
  •  | 
  •  

質問

ここで間違った方法でRubyを使用しているように感じます。正規表現 / [0-9A-Za-z] {3} / のすべての可能な一致を生成したいです

" 999" .succ => succ は使用できません。 " 1000" および" zZz&quot..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倍です:

それほどlessい方法はありませんか? alphaNumericX3 をパラメーター(alphaNumeric、3)から定義できる方法はありますか?

PS範囲に新しいクラスを定義できることは承知しています。しかし、それは間違いなく短くはありません。この次のブロックを上記のブロックよりも短く明確にできる場合は、次を実行してください:

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}

他のヒント

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'
scroll top