I have several strings that I need to compare with values in an array to determine which has the highest index number. For example, the data looks like this:
array = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']
v1 = "4"
v2 = "A"
v3 = "8"
How would I write it so that it would compare each value and return the fact that v2 is the winner based on the index number for A being 12?
A short version:
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
You could write:
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
I have assumed that array
may not be sorted.
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"
or
array.reverse.map(&:to_s).find(&[v1, v2, v3].method(:include?))
# => "A"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.