我有两个不同的数组,我需要一个方法来回复我:
array_1 = [1,2,3]
array_2 = ["a","b","c","d","e","f","g"]
def letter_to_number()
#what goes here?
end
letter_to_number("g") #return 1
letter_to_number("a") #return 1
letter_to_number("b") #return 2
letter_to_number("f") #return 3
我对如何做到这一点的任何方式都不满意。我觉得可能有一种更简单的方法。
答案 0 :(得分:2)
如果我理解正确,你的意思是得到这样的数字:
array1(repeat): 1 2 3 1 2 3 1 2 3
array2: a b c d e f g
您可以在array_2
中获取字母索引,按%
的长度计算模数(array_1
),并获取array_1
中的值使用此索引:
array_1[array_2.index("g") % array_1.length]
# => 1
我将留下如何为您制作这样的方法。
答案 1 :(得分:0)
def letter_to_number(array_1, array_2, letter)
array_1[array_2.index(letter) % array_1.size]
end
array_1 = [1,2,3]
array_2 = ["a","b","c","d","e","f","g"]
letter_to_number(array_1, array_2, "g") #=> 1
letter_to_number(array_1, array_2, "a") #=> 1
letter_to_number(array_1, array_2, "b") #=> 2
letter_to_number(array_1, array_2, "f") #=> 3
array_1 = [1,2,3,4]
array_2 = ["a","b","c","d","e","f","g"]
letter_to_number(array_1, array_2, "g") #=> 3
letter_to_number(array_1, array_2, "a") #=> 1
letter_to_number(array_1, array_2, "b") #=> 2
letter_to_number(array_1, array_2, "f") #=> 2
答案 2 :(得分:0)
上面的答案是正确的,除非需要处理一个角落案例,如下所示。
def letter_to_number(array_1, array_2, char)
index = array_2.index(char)
(index)? array_1[index % array_1.length] : -1
end