2.9 KiB
SELECTED RUBY METHODS
Here are some exercises to become more acquainted with the following Ruby methods:
.each.class.select.reject.flatten.permutation.to_a.first.last.count.reduce.uniq.shuffle.each_slice.sample.each_cons
1
Given the following array
arr = [["Live", "Laugh", "Love"], {hello: 'hi back'}, false, 333.333, nil, nil, ["Joy", "Joke", "Jerk"]]
-
Use
.eachand.classto print the class of each array element to the console -
Use
.selectand.classto return an array of only those elements whose class is Array. http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-select -
Use
.rejectand.classto return an array of only those elements whose class is not Hash. http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-reject -
Use
.flattenon the result of your previous.selectoperation to flatten out the array -
Use
.permutation.to_aon the flattened result to return all possible permutations of all the items within the inner arrays. -
Use
.countto get the number of those permutations.
2
Given the following array
numbers = [4, 7, 8, 7, 9, 0, 4]
-
Use
.permutation.to_aand.countto return a count of all permutations -
.selectonly those permutations where the.firstnumber is 7 and the.lastnumber is also 7, and return a.countof those permutations. -
Use
.reduceto get the sum of the array. -
Use
.reduceto get the product of the array.
3
Given the following array
strings = ["Paloma", "Grits", "Ziti", "Carbohydrates", "Grits", "Corn", "Wizard_robe", "Ziti", "Corn", "Corn", "Maize"]
and the empty hash
hash = {}
- Using
.eachand.uniq, populate the hash using the elements in the array as keys. Remember that keys must be unique, so don't include any double-ups. Set the values of those keys to "Fun" except for Maize, which is "Not Fun".
4
students = [
"Amber",
"Nicole",
"Christine",
"Dan",
"Ashleigh",
"Jordan",
"Alex",
"Emily",
"John",
"Sharon",
"Levi",
"Pauline",
"Masha",
"Matt",
"Andy",
"Sammy",
"Dominic",
"Vincent",
"Jesse",
"Juan",
"Josh",
"Derek"
];
-
Pretend that group projects are coming up again, and you have to split the class up into random groups of three. Use
.shuffleand.each_sliceto generate groups of three (there will be one remainder). http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-each_slice. -
Use
.sampleto return a single random student to be taken to jail. http://ruby-doc.org/core-2.1.4/Array.html#method-i-sample
5. Make your own problem
Look into the Ruby method .each_cons, http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-each_cons
Make your own problem where the answer should use .each_cons.