遍历 Ruby 中的字母表直到 X

Iterate through alphabet in Ruby until X

当使用输入 x 时,我试图遍历字母表直到那个点,所以如果我输入 44,我将通过此方法迭代到 18。

我可以在 SO 上看到很多用于迭代 a..z、a..zzz 等的方法,但很少有用于迭代定位 x 和输出相关字母的方法。是否有 ruby 将输入字母翻转为动态范围内的数字的方法?

def get_num(x)
  pos = x%26
   (1..pos).each do |c|
     puts c
     #outputs letter for position c
  # end      
end

get_num(44) # => Expected: 44%26 = 18; iterate 1 to 18 (pos) to get A..R list as output.

使用#Integer.chr方法,'a'..'z' == 97..122'A'..'Z' == 65..90即:

def get_num(x)
  pos = x%26
  (96+pos).chr
end

get_num(44)
#=>  "r"

def get_num(x)
  pos = x%26
  (64+pos).chr
end

get_num(44)
#=>  "R"

因此,要完成您的方法:

def get_num(x)
  pos = x%26
   (1..pos).each do |c|
    puts (c+64).chr 
  end      
end

get_num(44)
#=>
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R