Possible Duplicate:
check if value exists in array in Ruby
I have this method which loops through an array of strings and returns true if any string contains the string 'dog'. It is working, but the multiple return statements look messy. Is there a more eloquent way of doing this?
def has_dog?(acct) [acct.title, acct.description, acct.tag].each do |text| return true if text.include?("dog") end return false end
function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = 0; j < myArray. length; j++) { if (i != j) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } } return false; // means there are no duplicate values. }
Count(y => x == y) == 1); If the result of any of these expressions is false, that means your array has duplicates, otherwise all elements are unique.
In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise.
The condition to check is passed as a callback function to the every () method. This callback function is called for each element in the array — the element and index are passed as its parameters.
Checking whether All Array Elements Satisfy the Condition The every () method in Javascript tests all the elements of a given array against a condition and returns a boolean true on success. If any one element does not pass the test, false is returned. The condition to check is passed as a callback function to the every () method.
This callback function is called for each element in the array — the element and index are passed as its parameters. If the element satisfies the condition in the callback we need to return true, and false otherwise. We demonstrate the working of every () with a simple example — we will check if all elements of array are less than 10.
If you want to check if one or more elements fulfill the condition, there is some () method. The some () method executes the callback function once for each element present in the array until it finds the one where callback returns a truthy value. If such an element is found, some () method immediately returns true.
Use Enumerable#any?
def has_dog?(acct) [acct.title, acct.description, acct.tag].any? { |text| text.include? "dog" } end
It will return true
/false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With