Does an array or string
contain a specific value? With Ruby we can use a loop or an iterator to search. But another approach can be used.
With include, we can search an array for a value in a single method call. This is easier to read and easy to use. We must include a question mark at the end of include.
Let us begin. This program uses an array of 3 integers. It then searches the array with "include" 2 times. The first tested value, 200, is found.
values = [10, 200, 3000] # See if array includes this value. if values.include?(200) puts "ARRAY CONTAINS 200" end # See if array does not include this value. if !values.include?(999) puts "ARRAY DOES NOT CONTAIN 999" endARRAY CONTAINS 200 ARRAY DOES NOT CONTAIN 999
String
includeIs one string
contained within another? The "include?" method in Ruby tells us. It searches one string
for a second string
. It returns true or false.
string
"plato" contains the string
"to". It does not contain the string
"not".string
"plato" does not include the string
"PLA".value = "plato" # String includes "to". if value.include? "to" puts "1" end # String does not include "not". if !value.include? "not" puts "2" end # String does not include "PLA" uppercase. if !value.include? "PLA" puts "3" end1 2 3
In Ruby, a method that ends in a question mark is a predicate method, one that returns true or false. With "include we get a boolean result.
Methods that use iterators usually will involve more code than "include." But they also may be more powerful—you can add more steps to the iterator than you can to "include."