Ruby Methods Cheat Sheet Flashcards
Find the characters in specific positions in a STRING.
“string”[1..3]
Find the elements in specific positions in an ARRAY.
array[1..2]
Find the value of specific key in a HASH.
hash[“key”]
Find first or last value(s) in a STRING.
“string”[0]
[-1]
[-3…-1]
Find first or last value(s) in an ARRAY (3 ways)
.first / .last
.first(n) / .last(n)
Array[0] or [-1]
Find first or last value(s) in a HASH
Not necessary. Can do for multl-dimensional hash, but that’s too advanced for now. Ignore.
Find the positions of specific characters in a STRING.
What is returned?
“string”.index(“s”)
Returns the first location
Find the positions of specific elements in an ARRAY.
What is returned?
How do you find elements that fulfills a specific criteria test?
array.index(“element1”)
Returns the first location.
With a block:
array.index {|x| x == “apple”}
Find the key of a certain value or the value of a certain key in a HASH.
hash. key(“xxx”) gets the key
hash. value(“xxx”) gets the value
Get all the keys or values of a HASH
hash. keys
hash. values
All the ways to get number of all characters in a STRING
2
.length
.size
** ONLY exception to remember is that you can’t COUNT STRINGS.
All the ways to get number of all elements in an ARRAY
3
.length
.size
.count
All the ways to get number of all key-value pairs in a HASH
3
.length
.size
.count.
Get the total number of all elements that pass a certain test in an ARRAY
.count with a block:
array.count {|x| x > 2}
Get the total number of all key-value pairs that pass a certain test in a HASH
.count with a block:
array.count {|key, value| key > 2}