如何获取 Rails 中的数组元素 3

How to get array element in Rails 3

我在 rails 中有一个像这样的数组 [["SWD", "150325006"], ["GOODS", "150325006"]] 3.I 想要获取那些类型为 "SWD" 的数字。请检查下面的代码。

payment_controller.rb

class PaymentsController < ApplicationController

    def payment
        @payment=Vendor.new
        respond_to do |format|
            format.html 
            format.js
        end

    end
    def check_type  
        if params[:commit]=="submit"
            @vendor_type = PaymentVendor.where(:v_name => params[:v_name]).map{|v|[v.v_catagory ,v.Receipt_No]}
            #@vendor_type = PaymentVendor.where(:v_name => params[:v_name]).pluck(:v_catagory)


        else
            @v_name=Vendor.where(:s_catagory => params[:payment][:s_catagory] ).pluck(:v_name)
        end
    end
end

@vendor_type 正在给出这样的值 [["SWD", "150325006"], ["GOODS", "150325006"]]。请帮助我。

▶ arr = [["SWD", "150325006"], ["GOODS", "150325006"]]
#⇒ [["SWD", "150325006"], ["GOODS", "150325006"]]
▶ arr.select { |e| e.first == 'SWD' }.map(&:last)
#⇒ ["150325006"]
@vendor_type = [["SWD", "150325006"], ["GOODS", "150325006"],["GOODS", "150325006sdfs"],["SWD", "150325006sdff"]]

output = []
@vendor_type.each do |i|
   if i.first == "SWD"
      output << i[1]
   end
end
puts output

试试这个:

> array = [["SWD", "150325006"], ["GOODS", "150325006"]]
 => [["SWD", "150325006"], ["GOODS", "150325006"]] 
> array.select{|e| e[0] == "SWD" }.map(&:last)
 => ["150325006"] 

您可以使用 assoc:

array = [["SWD", "150325006"], ["GOODS", "150325006"]]

array.assoc('SWD').last    
#=> "150325006"