rails从hash数组中选择最大值

时间:2015-01-08 07:20:40

标签: ruby-on-rails arrays hash

我有一个像这样的哈希数组,我想取这个

的最大值
data = [{name: "abc", value: "10.0"}, {name: "def", value: "15.0"}, {name: "ghi", value: "20.0"}, {name: "jkl", value: "50.0"}, {name: "mno", value: "30.0"}]

我想选择哈希数组的最大值,我想要的输出就像数据:" 50.0"

我有可能做到这一点,我试过这个但看起来似乎没有用,只是给我一个错误

data.select {|x| x.max['value'] }

任何帮助都将非常感激

3 个答案:

答案 0 :(得分:8)

在Ruby中有很多方法可以做到这一点。这是两个。您可以将块传递给Array#max,如下所示:

  > data.max { |a, b| a[:value] <=> b[:value] }[:value]
   => "50.0"

或者您可以使用Array#map:value中删除Hash条目:

  > data.map { |d| d[:value] }.max
   => "50.0"

请注意,您可能希望使用#to_fFloat(...)来避免进行字符串 - 字符串比较,具体取决于您的用例。

答案 1 :(得分:1)

较短版本的kranzky回答:

data.map(&:value).max

答案 2 :(得分:0)

您还可以对哈希数组进行排序并按索引获取值。

def main():

    def input_stocks():
        tot_pr = 0

        while True:
            stock_name = input("\nEnter Stock Name: ")
            shares_bought = float(input("\nNumber of Shares bought: "))
            stock_pp = float(input("Enter stock purchasing price: "))
            stock_sp = float(input("Enter stock selling price: "))
            commision = float(input("Enter broker Commision: "))
            peaceout = input("Continue or exit? (case sensitive):")
            if peaceout == 'quit':
                return stock_name,shares_bought,stock_pp,stock_sp,commision


    def calc():
        amount_paid = shares_bought * stock_pp

        paid_commision_bought = amount_paid * commision

        stock_sold = shares_bought * stock_sp

        paid_commision_sold = stock_sold * commision

        pl = (stock_sold - paid_commision_sold) - (amount_paid + paid_commision_bought)

        tot_pr = tot_pr + pl

    def output():
        print("\nStock Name:", stock_name)
        print("Amount paid: $", format(amount_paid,',.2f'))
        print("Paid commision bought: $", format(paid_commision_bought,',.2f'))
        print("Stock sold $", format(stock_sold,',.2f'))
        print("Paid commision sold: $", format(paid_commision_sold,',.2f'))
        print("Profit or Loss: $", format(pl,',.2f'))
        print("Total Profit thus far: $", format(tot_pr,',.2f'))
        return stock_name,amount_paid,paid_commision_bought,paid_commision_sold,pl,tot_pr

    output()
main()

如果您还需要最小,第二大等,也很有用。