Ruby Methods Flashcards
What is the ruby method that converts a non-string element into a string?
.to_s
What is the ruby method that converts a non-INTEGER element into an integer?
.to_i
What is the ruby method that converts a string into all capital letters?
.upcase
What is the ruby method that converts a string into all lowercase letters?
.downcase
What is the ruby method that changes the case of each character in a string?
.swapcase
What is the ruby method that capitalizes the first character of a string?
.capitalize
.capitalize will capitalize:
A. The first letter of a string
B. The first character of a string
C. All characters in the string
B. The first character of a string (So, if the string starts with a space, no element will be capitalized)
What does the method == mean?
BOOLEAN OPERATOR: Evaluates if elements are equal to one another. Returns TRUE or FALSE.
What does the method || mean?
BOOLEAN OPERATOR: Evaluates if A or B are true. Returns TRUE or FALSE.
What does the method && mean?
BOOLEAN OPERATOR: Evaluates if A and B are true. Returns TRUE or FALSE.
.even?
Test whether an integer is even. Returns true or false.
.abs
Absolute value for an integer.
num = -1234 # variable assignment positive = num.abs # => 1234
p
Writes to console. This works like puts but displays values such as nil explicitly.
Example:
p “Jonathan”
Public Methods
Can be called by anyone—no access control is enforced. Methods are public by default (except for initialize, which is always private).
Protected Methods
Can be invoked only by objects of the defining class and its sub- classes. Access is kept within the family.
If a method is protected, it may be called by any instance of the defining class or its subclasses. If a method is private, it may be called only within the context of the calling object—it is never possible to access another object’s private methods directly, even if the object is of the same class as the caller.
Private Methods
Cannot be called with an explicit receiver—the receiver is always the current object, also known as self. This means that private methods can be called only in the context of the current object; you can’t invoke another object’s private methods.
If a method is protected, it may be called by any instance of the defining class or its subclasses. If a method is private, it may be called only within the context of the calling object—it is never possible to access another object’s private methods directly, even if the object is of the same class as the caller.
.dup
Used to duplicated objects. Does not work for numbers, but does work for strings, hashes, arrays, and ranges.
Can be used on variables to avoid aliasing.
.freeze
Used to freeze objects. This means it prevents modifications to the object. It does not, however, prevent re-assigning.
Example:
a = [4,5,6]
a. freeze
a. pop
=> RuntimeError: can’t modify frozen Array
a = [4,5,6] #reassigns
a.pop
6 # popped the 6 from the end
a # calls variable
[4,5] #returns minus the popped digit
.scan
Scan RETURNS AN ARRAY of substrings that match a given pattern.
Example using Regex:
string.scan(/[\w’]+/)
.sort_by
Takes a code block. Not an iterator, but just a block telling the code what to sort_by.
Example:
%w(a aa aaaaaaaaaa aaa).sort_by { |word| word.length}
returns:
[“a”, “aa”, “aaa”, “aaaaaaaaaa”]
.each
The method each is an iterator—a method that invokes a block of code repeatedly.
Example:
[1,2,3,4,5,6].each do |i|
puts “I am the #{i} iteration.”
end
I am the 1 iteration. I am the 2 iteration. I am the 3 iteration. I am the 4 iteration. I am the 5 iteration.
.find
Find takes a block that tells Ruby what do find in an array.
Example:
[1,3,5,7,9].find{|v|v*v>30}
If no element is found, it returns nil.
=> 7
It only finds the first occurernce that is true. To find all, you’d have use find_all.
.find_all
Find_all takes a block that tells Ruby what do find in an array.
Example:
[1,3,5,7,9].find_all{|v|v*v>30}
If no element is found, it returns AN EMPTY ARRAY, not nil.
=> [7,9]
.succ
The succ method increments a string value.
Example:
“a”.succ # b
Also works on numbers:
456.succ # 457
What is the method to increment a string value?
.succ
.inject
this is slightly more difficult to understand. the basis premise is that. it divides once, becomes a fraction, which is the current result. each successive current result is then divided by the next digit.
Inject allows you to accumulate a value across the members of a collection. Inject must work with 2 variables, meaning you must supply TWO THINGS to the pipes. This method applies a function or operation to the first two elements in the collection and then applies the operation to the result of this computation and to the third element, and so on, until all elements in the collection have been used.
Example:
Simple addition: (just add the numbers together)
[2,3,4,5,6].inject {|i, x| i + x}
=> 20
Division:
[2.0,3,4,5,6].inject {|i, x| i / x}
=> 0.005555555555555556
Multiplication: *the multiplication method has to have a default of 1 or else the current sum would be 0. multiplication x 0 would yield 0. Of course, if zero is anywhere in the collection, the result is 0. So, should probably check to see if include?0
[2,3,4,5,6].inject {|i, x| i * x}
=>720
the steps are: Current result: 1 (default) current result x 2 = 2 Current result: 2 current result x 3 = 6 current result: 6 current result x 4 = 24 current result = 24 current result x 5 = 120 current result x 6 = 720
Special Syntax
[1,3,5,7].inject(:+) # => 16
[1,3,5,7].inject(:*) # => 105
Special Syntax for inject method
[1,3,5,7].inject(:+) # => 16
[1,3,5,7].inject(:*) # => 105
.to_enum
Used on collections to make them able to be iterated through (individually).
Example:
b = [5,10,14,18,25,30].to_enum
b. next # 5
b. next # 10
b. next # 14
Example with hash:
b = { name: “bobby”, age: 27, hometown: “hoboken” }.to_enum
b. next # => [:name, “bobby”]
b. next # => [:age, 27]
You can all most of the internal methods without a block and get this same effect.
.each_with_index
This invokes its host class’s each method, returning successive values along with an index:
Example:
result = [ ]
[ ‘a’, ‘b’, ‘c’ ].each_with_index {|item, index|
result «_space;[item, index] }
result # => [[“a”, 0], [“b”, 1], [“c”, 2]]
.each_char
Passes each character in str to the given block, or returns an enumerator if no block is given.
Example:
“hello”.each_char {|c| print c, ‘ ‘ }
produces:
h e l l o
.with_index
Is basically used to combing .each_with_index, with other methods. For example:
result = []
“cat”.each_char.with_index {|item, index| result «_space;[item, index] } result # => [[“c”, 0], [“a”, 1], [“t”, 2]]
.enum_for( )
Creates a new Enumerator which will enumerate by on calling method on obj.
method
the method to call on obj to generate the enumeration
args
arguments that will be passed in method in addition to the item itself. Note that the number of args must not exceed the number expected by method
Examples:
str = “xyz”
enum = str.enum_for(:each_byte) enum.each { |b| puts b } # => 120 # => 121 # => 122
# protect an array from being modified by some_method a = [1, 2, 3] some_method(a.to_enum)
Example:
enum = “cat”.enum_for(:each_char) enum.to_a # => [“c”, “a”, “t”]
.squeeze
Squeeze removes beginning and trailing spaces from strings. Removes all space - down to 1 space on either side.
Example:
” the best day “.squeeze
=> “ the best day “
A loop from 0 to 12 by 3 can be written as follows:
0.step(12, 3) {|x| print x, “ “ }
.step
Step passes two numbers to the original number. The ending number and the increment number.
0.step(12, 3) {|x| print x, “ “ }
.grep
Using the grep method in Enumerable, we could iterate over only those lines that end with a d:
File.open(“ordinal”).grep(/d$/) do |line| puts line
end
produces:
second third
.strip
strips whitespace from a string