过滤并计算一个ruby哈希数组

时间:2015-12-03 02:57:51

标签: arrays ruby hash filter aggregate

在我的ruby脚本中,我有一系列哈希,如

arr[{acnt=>"001"},{acnt=>"001"},{acnt=>"002"},{acnt=>"002"},{acnt=>"003"}]

我想根据每个帐户计算数字,以便输出如下:

output[{"001"=>2}, {"002"=>2}, {"003"=>1}]

我该怎么办?

谢谢,乔恩

2 个答案:

答案 0 :(得分:2)

编辑:我刚刚注意到了@ muistooshort的评论,除了(简单的)最后一步(map { |k,v| { k=>v } })之外,他提出了与我相同的建议。 μ,如果你想发一个答案,我会删除我的。

有很多方法可以做到这一点。这是一个:

arr = [{ "acnt"=>"001" }, { "acnt"=>"001" }, { "acnt"=>"002" },
       { "acnt"=>"002" }, { "acnt"=>"003"}]

arr.flat_map(&:values).
    each_with_object(Hash.new(0)) { |s,h| h[s] += 1 }.
    map { |k,v| { k=>v } }
  #=> [{"001"=>2}, {"002"=>2}, {"003"=>1}]

步骤如下:

a = arr.flat_map(&:values)
  #=> ["001", "001", "002", "002", "003"] 
h = a.each_with_object(Hash.new(0)) { |s,h| h[s] += 1 }
  #=> {"001"=>2, "002"=>2, "003"=>1} 
h.map { |k,v| { k=>v } }
  #=> [{"001"=>2}, {"002"=>2}, {"003"=>1}] 

答案 1 :(得分:1)

尝试以下方法:

#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,assign)int currentQuestionIndex;
@property(nonatomic,copy)NSArray *questions;
@property (weak, nonatomic) IBOutlet UILabel *questionLabel;
@end

@implementation ViewController

-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName: nibNameOrNil bundle: nibBundleOrNil];
    if (self) {
        //fill two array
        self.questions =@[@"Who is the president of US?",@"What is 7 + 7?",@"What is the capital of Vermont?"];
        }
    //return the address of new object
    return self;
}

- (IBAction)showQuestion:(id)sender
{
    // Step to the next question
    self.currentQuestionIndex++;

    // Am I pas the last question?
    if (self.currentQuestionIndex == [self.questions count]) {

        // Go back to the first question
        self.currentQuestionIndex = 0;
    }

    // Get the string at the index in the questions array
    NSString *question = self.questions[self.currentQuestionIndex];

    // Display the string in the question label
    self.questionLabel.text = question;
    }

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    }

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end