Ruby Methods Flashcards

1
Q

What is the ruby method that converts a non-string element into a string?

A

.to_s

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the ruby method that converts a non-INTEGER element into an integer?

A

.to_i

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the ruby method that converts a string into all capital letters?

A

.upcase

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the ruby method that converts a string into all lowercase letters?

A

.downcase

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the ruby method that changes the case of each character in a string?

A

.swapcase

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the ruby method that capitalizes the first character of a string?

A

.capitalize

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

.capitalize will capitalize:

A. The first letter of a string
B. The first character of a string
C. All characters in the string

A

B. The first character of a string (So, if the string starts with a space, no element will be capitalized)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does the method == mean?

A

BOOLEAN OPERATOR: Evaluates if elements are equal to one another. Returns TRUE or FALSE.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does the method || mean?

A

BOOLEAN OPERATOR: Evaluates if A or B are true. Returns TRUE or FALSE.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does the method && mean?

A

BOOLEAN OPERATOR: Evaluates if A and B are true. Returns TRUE or FALSE.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

.even?

A

Test whether an integer is even. Returns true or false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

.abs

A

Absolute value for an integer.

num = -1234 # variable assignment
positive = num.abs # => 1234
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

p

A

Writes to console. This works like puts but displays values such as nil explicitly.

Example:

p “Jonathan”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Public Methods

A

Can be called by anyone—no access control is enforced. Methods are public by default (except for initialize, which is always private).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Protected Methods

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Private Methods

A

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.

17
Q

.dup

A

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.

18
Q

.freeze

A

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

19
Q

.scan

A

Scan RETURNS AN ARRAY of substrings that match a given pattern.

Example using Regex:

string.scan(/[\w’]+/)

20
Q

.sort_by

A

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”]

21
Q

.each

A

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.
22
Q

.find

A

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.

23
Q

.find_all

A

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]

24
Q

.succ

A

The succ method increments a string value.

Example:

“a”.succ # b

Also works on numbers:
456.succ # 457

25
Q

What is the method to increment a string value?

A

.succ

26
Q

.inject

A

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

27
Q

Special Syntax for inject method

A

[1,3,5,7].inject(:+) # => 16

[1,3,5,7].inject(:*) # => 105

28
Q

.to_enum

A

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.

29
Q

.each_with_index

A

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 &laquo_space;[item, index] }
result # => [[“a”, 0], [“b”, 1], [“c”, 2]]

30
Q

.each_char

A

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

31
Q

.with_index

A

Is basically used to combing .each_with_index, with other methods. For example:

result = []
“cat”.each_char.with_index {|item, index| result &laquo_space;[item, index] } result # => [[“c”, 0], [“a”, 1], [“t”, 2]]

32
Q

.enum_for( )

A

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”]

33
Q

.squeeze

A

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 “

34
Q

A loop from 0 to 12 by 3 can be written as follows:

A

0.step(12, 3) {|x| print x, “ “ }

35
Q

.step

A

Step passes two numbers to the original number. The ending number and the increment number.

0.step(12, 3) {|x| print x, “ “ }

36
Q

.grep

A

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

37
Q

.strip

A

strips whitespace from a string