如何从哈希中将值提取到单独的数组中?

时间:2018-03-14 08:27:02

标签: ruby

我该如何改变:

array_of_hash = [{"month"=>"January", "count"=>67241},
                 {"month"=>"February", "count"=>60464},
                 {"month"=>"March", "count"=>30403}] 

对此:

month = ["January", "February", "March"]
count = [67241, 60464,30403]

4 个答案:

答案 0 :(得分:3)

要提取单个值(例如'month'),您可以使用map

array_of_hash.map { |hash| hash['month'] }
#=> ["January", "February", "March"]

可以将其扩展为返回'month'count'的值:

array_of_hash.map { |h| [h['month'], h['count']] }
#=> [["January", 67241], ["February", 60464], ["March", 30403]]

还有一种方法可以同时获取多个值 - values_at

array_of_hash.map { |h| h.values_at('month', 'count') }
#=> [["January", 67241], ["February", 60464], ["March", 30403]]

然后可以通过transpose

重新排列生成的数组
array_of_hash.map { |h| h.values_at('month', 'count') }.transpose
#=> [["January", "February", "March"], [67241, 60464, 30403]]

可以使用Ruby的array decomposition

将两个内部数组分配给单独的变量
months, counts = array_of_hash.map { |h| h.values_at('month', 'count') }.transpose

months #=> ["January", "February", "March"]
counts #=> [67241, 60464, 30403]

答案 1 :(得分:2)

一个简单的解决方案是迭代哈希数组并将所需的值添加到两个单独的数组中:

months = []
counts = []
array_of_hash.each do |hash|
  months << hash["month"]
  counts << hash["count"]
end

但您也可以使用each_with_object

months, count = array_of_hash.each_with_object([[], []]) do |hash, accu|
  accu[0] << hash["month"]
  accu[1] << hash["count"]
end

或迭代两次并获得月份并分别计算:

months = array_of_hash.map { |hash| hash["month"] }
counts = array_of_hash.map { |hash| hash["count"] }

答案 2 :(得分:1)

months, counts =
  %w|month count|.map { |key| array_of_hash.map { |h| h[key] } }
private void getSpecificTicketFromFirebase() {
Timber.d("Inside Pull Data %s ",firebaseManager.getFireBaseUser().getUid()) ;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("user").child(firebaseManager.getFireBaseUser().getUid()).child("ticket");
FirebaseDatabase.getInstance().getReference().addValueEventListener(new ValueEventListener() {
  int i=0;
  @Override public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot data : dataSnapshot.getChildren()) {
      passengerData = data.getValue(PassengerViewModel.class);
      passengerViewModel.add(passengerData);
      Timber.d("Passenger Name %s index %s key %s",passengerViewModel.get(i).getFromStationName(),i,data.child("passengerName"));
      i++;
    }
  }

  @Override public void onCancelled(DatabaseError databaseError) {
    Timber.e(databaseError.getDetails());
    Timber.e(databaseError.getMessage());
    Timber.e(databaseError.toException());
  }
});

答案 3 :(得分:0)

{{1}}