当使用输入x
时,我试图遍历字母表到那个点,所以,如果我输入44,我将从这个方法迭代到18。
我可以看到很多方法,所以对于迭代a.z,a..zzz等,但是迭代定位x和输出相关字母的方法较少。在动态范围内,是否有将输入字母翻转为数字的红宝石方法?
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.
发布于 2022-02-04 18:32:54
使用#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
https://stackoverflow.com/questions/70994491
复制