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
- Is the zeroth element in every array a string?
- Is the second element in every array an integer?
Thanks!
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.
Try using all?
:
all_match = array.all? {|inner_array|
inner_array[0].kind_of?(String) && inner_array[1].kind_of?(Fixnum)
}
精彩评论