ruby - 在 Ruby 中生成不同的范围,即所有可能的/[0-9A-Za-z]{3}/

标签 ruby range

我觉得我在这里使用 Ruby 的方式是错误的:我想为正则表达式 /[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}

我的问题有两个:

有没有一种不那么难看的方法,有没有一种方法 alphaNumericX3可以从参数 (alphaNumeric, 3) 定义?

PS 我知道我可以为范围定义一个新类。但这绝对不短。如果您可以使下一个 block 比上面的 block 更短、更清晰,请执行以下操作:

class AlphaNum
  include Comparable
  attr :length
  def initialize(s)
    @a=s.chars.to_a
    @<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8089828b9884d1ac8dc28089828b9884" rel="noreferrer noopener nofollow">[email protected]</a>
  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('') }

关于ruby - 在 Ruby 中生成不同的范围,即所有可能的/[0-9A-Za-z]{3}/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/613697/

相关文章:

ruby-on-rails - 在 Rails 3 中动态创建路由别名

python - 如何在 Python 中使用 Pandas 创建一系列数字

javascript - 如何在javascript中计算周和月的日期范围?

c - 将 int 保存为 char?

c++ - 范围的切换语句

python - 跳过python中范围函数中的值

ruby-on-rails - 无法从 post_id 找到出价

ruby-on-rails - ruby on rails i18n 和 number_to_currency 负值

ruby-on-rails - 在 Rails 中使用没有父 ID 的嵌套资源

ruby-on-rails - heroku Cedar 上的 CSV