2

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!

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You say any? in the first sentence, but the code example uses all?.
1

Try using all?:

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

1 Comment

I don't want to delete elements. I just want to verify the array's integrity before doing stuff with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.