mbm
mbm

Reputation: 1922

Testing data in Ruby Arrays

Say I have an array of arrays in Ruby,

array = [["bob", 12000, "broke", "ugly"],
         ["kelly", 50000, "rich", "attractive"]]

Each subarray is just a record. What's syntactically the most elegant construct for testing certain elements of each subarray for certain conditions, such as

Thanks!

Upvotes: 2

Views: 107

Answers (2)

Swanand
Swanand

Reputation: 12426

Since you mentioned every element, the idiomatic way is to use all? enumerable. Like this:

array = [["bob", 12000, "broke", "ugly"],
         ["kelly", 50000, "rich", "attractive"]]

array.all? { |element| 
  # check whatever you would like to check
  # check if zeroth element is String or not
  element.first.is_a?(String) # this would mean that you are assuming element is a collection, since first generally works on a collection
}

Enumerable is a good place to start.

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163298

Try using all?:

all_match = array.all? {|inner_array|
    inner_array[0].kind_of?(String) && inner_array[1].kind_of?(Fixnum)
}

Upvotes: 1

Related Questions