Mixed Ruby revision Flashcards
Which operator returns a new array containing the elements common to both values, without duplicates?
The & operator
Which operator returns a new array by joining arrays and removing duplicates?
The | operator
Which method returns a new array containing the original array elements in reverse order?
The reverse method (e.g. array.reverse)
Reverse the order of the elements in the array below:
elements = [1, 3, 5, 7, 9]
elements.reverse
NB If you use the reverse method without (!) and don’t save it to a new variable, it will just reverse it once and keep the original value.
Which 2 methods return the number of elements in an array?
array.length or array.size
NB you can also use .count with no arguments passed to it and it will perform the same way as these on arrays. It’s not the same as these two though (.length and .size can be used interchangably) - you can do more with .count by passing it arguments. You also cannot use .count on a string without an argument.
Which method returns a new array with the elements sorted?
array.sort
Which method returns a new array with duplicate values removed from the array?
array.uniq
(array.uniq! removes duplicates in place.)
Which method safeguards an array, preventing it from being modified?
array.freeze
Which method returns true if an object is present in an array and false otherwise?
array.include?(obj)
Which method returns the element with the minimum value in an array?
array.min
Which method returns the element with the maximum value in an array?
array.max
How could you iterate over an array of elements and puts each element to the console, with a for loop?
array = [“apple”, “dragonfruit”, “plum”]
for x in array
puts “Value: #{x}” # alternatively, puts x
end
How would you access the value associated with “Lena” within the following hash?
ages = { “Marge” => 28, “Lena”=> 19, “Hamish” => 42 }
ages[“Lena”]
Why use symbols instead of strings as hash keys?
Using symbols not only saves time when doing comparisons, but also saves memory, because they are only stored once.
Create a hash (h) containing a key (name) and its value (“Flora”). Show 2 ways of doing this.
h = {name: “Flora”} # This method is shorter!
h = {:name => “Flora”}