如何在多维数组中找到最长的字符串?

时间:2014-02-20 15:01:38

标签: ruby arrays sorting multidimensional-array

我正在尝试从多维数组中获取最长的字符串,但由于某种原因它无法正常工作。

这就是我所拥有的:

a = 
["MAKKGKPRPDHRPPAHNPHYAHDPPPYSQQQPPLQQQNYAQQMNRQHARPRPSPPSEVSDCVKYSLFLYNCIFWVSMHSS"],
["MHHGGGGGNRQHARPRPSPPSEVSDCVKYSLFLYNCIFWVSMHSS"], ["MTYINLGVTRTGDLMIGRHRP"],
["MRIYNRVCFQTAGCYLQNLVTTSIQPARVWTY"], ["MAACGLGRVFSAFKVDEMD"], 
["MPSGFVGKRSGFCQFCCSHI"], ["MTYSTAKEGAYPFRNFN"]]

p a.max_by{|v|v}[0]  # => "MTYSTAKEGAYPFRNFN"

有人可以让我知道我做错了吗?

4 个答案:

答案 0 :(得分:7)

=> a.flatten.max_by(&:size)
=> # "MAKKGKPRPDHRPPAHNPHYAHDPPPYSQQQPPLQQQNYAQQMHHGGGGGNRQHARPRPSPPSEVSDCVKYSLFLYNCIFWVSMHSS"

答案 1 :(得分:5)

a = [
    ["MAKKGKPRPDHRPPAHNPHYAHDPPPYSQQQPPLQQQNYAQQMHHGGGGGNRQHARPRPSPPSEVSDCVKYSLFLYNCIFWVSMHSS"],
    ["MHHGGGGGNRQHARPRPSPPSEVSDCVKYSLFLYNCIFWVSMHSS"],
    ["MTYINLGVTRTGDLMIGRHRP"],
    ["MRIYNRVCFQTAGCYLQNLVTTSIQPARVWTY"],
    ["MAACGLGRVFSAFKVDEMD"],
    ["MPSGFVGKRSGFCQFCCSHI"],
    ["MTYSTAKEGAYPFRNFN"]
]
p a.max_by { |v| v[0].size }[0]

输出:

"MAKKGKPRPDHRPPAHNPHYAHDPPPYSQQQPPLQQQNYAQQMHHGGGGGNRQHARPRPSPPSEVSDCVKYSLFLYNCIFWVSMHSS"

只需指定v,就可以对每个元素(单元素数组)进行比较。它们按字典顺序进行比较。

答案 2 :(得分:2)

这应该有效:

a.max_by { |v| v.first.size }[0]

答案 3 :(得分:2)

=> a = [["MAKKGKPRPDHRPPAHNPHYAHDPPPYSQQQPPLQQQNYAQQMHHGGGGGNRQHARPRPSPPSEVSDCVKYSLFLYNCIFWVSMHSS"],
        ["MHHGGGGGNRQHARPRPSPPSEVSDCVKYSLFLYNCIFWVSMHSS"],
        ["MTYINLGVTRTGDLMIGRHRP"],
        ["MRIYNRVCFQTAGCYLQNLVTTSIQPARVWTY"],
        ["MAACGLGRVFSAFKVDEMD"],
        ["MPSGFVGKRSGFCQFCCSHI"],
        ["MTYSTAKEGAYPFRNFN"]
    ]

=> a.flatten.sort_by(&:length).last

#=> "MAKKGKPRPDHRPPAHNPHYAHDPPPYSQQQPPLQQQNYAQQMHHGGGGGNRQHARPRPSPPSEVSDCVKYSLFLYNCIFWVSMHSS"