如何将字符串与数组进行比较以确定最高索引值?

时间:2014-08-12 01:23:20

标签: ruby arrays string compare

我有几个字符串需要与数组中的值进行比较,以确定哪个字符串具有最高的索引号。例如,数据如下所示:

array = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']

v1 = "4"
v2 = "A"
v3 = "8"

我如何编写它以便比较每个值并根据A的索引号为12返回v2为胜者的事实?

3 个答案:

答案 0 :(得分:2)

简短版本:

array = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']

target = [4, "A", 8]
target & array  #=> [4, "A", 8]
array  & target #=> [4, 8, "A"]

(array & target ).last #=> "A"

target = ["B", "C"]
(array & target ).last #=> nil

答案 1 :(得分:1)

你可以写:

array = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']
a = array.map(&:to_s)
  #=> ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]

target = ["4", "A", "8"]
(target & a).empty? ? nil : a[target.map { |s| a.index(s) }.compact.max]
  #=> "A"

target = ["B", "C"]
(target & a).empty? ? nil : a[target.map { |s| a.index(s) }.compact.max]
  #=> nil

我假设array可能没有排序。

答案 2 :(得分:1)

array = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']

v1 = "4"
v2 = "A"
v3 = "8"

array.reverse.map(&:to_s).find { |e| [v1, v2, v3].include?(e) }
# => "A"

array.reverse.map(&:to_s).find(&[v1, v2, v3].method(:include?))
# => "A"