Ruby Flashcards

1
Q

Bloks

A

In Ruby, blocks are snippets of code that can be created to be executed later. Blocks are passed to methods that yield them within the do and end keywords.

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

IMPLICIT BLOCKS AND THE yield KEYWORD

A

Implicit block passing works by calling the yield keyword in a method. The yield keyword is special. It finds and calls a passed block, so you don’t have to add the block to the list of arguments the method accepts.Because Ruby allows implicit block passing, you can call all methods with a block. If it doesn’t call yield, the block is ignored.

irb> “foo bar baz”.split { p “block!” }
=> [“foo”, “bar”, “baz”]
If the called method does yield, the passed block is found and called with any arguments that were passed to the yield keyword.

def each
  return to_enum(:each) unless block_given?
  i = 0
  while i < size
    yield at(i)
    i += 1
  end
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

EXPLICITLY PASSING BLOCKS

A

We can explicitly accept a block in a method by adding it as an argument using an ampersand parameter (usually called &block). Since the block is now explicit, we can use the #call method directly on the resulting object instead of relying on yield.

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

Proc

A

A “proc” is an instance of the Proc class, which holds a code block to be executed, and can be stored in a variable. To create a proc, you call Proc.new and pass it a block.

proc = Proc.new { |n| puts “#{n}!” }

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

&:

A

[1,2,3].map(&:to_s)

This example shows a way of calling #to_s on each element of the array. In the first one, a symbol, prefixed with an ampersand, is passed, which automatically converts it to a proc by calling its #to_proc method.

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

lambdas

A

Lambdas are essentially procs with some distinguishing factors. They are more like “regular” methods in two ways: they enforce the number of arguments passed when they’re called and they use “normal” returns.

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

.to_s

A

to_s() public

  • api_doc
    1) Returns a string representing obj. The default to_s prints the object’s class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns “main”.
2)Returns self.
If called on a subclass of String, converts the receiver to a String object.
  • codewars: to convert an integer to binary:> 9.to_s(2)
    => “1001”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

.count

A

count(p1) public
Returns the number of elements.

If an argument is given, counts the number of elements which equal obj using ==.

If a block is given, counts the number of elements for which the block returns a true value.

ary = [1, 2, 4, 2]

ary. count #=> 4
ary. count(2) #=> 2
ary. count { |x| x%2 == 0 } #=> 3

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

.select vv .reject

A
def friend(friends)
  friends.select { |name| name.length == 4 }
end
def friend(friends)
  friends.reject { |name| name.length != 4 }
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

memoization

A

Memoization is a technique you can use to speed up your accessor methods. It caches the results of methods that do time-consuming work, work that only needs to be done once.

  1. using the conditional assignment operator: ||=
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

When should you memoize?

A

When you’ve got duplicated database calls (like current_user above)
When you’ve got expensive calculations
When you’ve got repeated calculations that don’t change
Memoization is useful because it allows us to do some work only once and then have it available via an instance variable.

Memoization shouldn’t be used with methods that take parameters:
Or with methods that use instance variables (full_nsme`)

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

Garbage Collection

A

GC - механизм, обеспечивающий автоматическое управление памятью без вмешательства программиста. They:
allocate memory for new objects
identify garbage objects
reclaim memory from garbage objects

gc (wiki) -is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program.

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

What is method_missing?

A

is a method that ruby gives you access inside of your objects a way to handle situations when you call a method that doesn’t exist.

When you send a message to an object, the object executes the first method it finds on its method lookup path with the same name as the message. If it fails to find any such method, it raises a NoMethodError exception - unless you have provided the object with a method called method_missing. The method_missing method is passed the symbol of the non-existent method, an array of the arguments that were passed in the original call and any block passed to the original method.

  def method_missing(m, *args, &amp;block)  
    puts "There's no method called #{m} here -- please try again."  
  end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Ruby modules

A
Ruby module is a collection of methods and constants.
Most Ruby developers are familiar with using modules to share behavior.
Modules serve two purposes in Ruby, namespacing and mixin functionality.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

4 Simple Memoization Patterns in Ruby (And One Gem)

A
  1. Super basic memoization ‘||=’
  2. multi-lines ‘ || = begin … end’
    note!: nil, false. use ‘if defined?’
  3. what about parameters?
    use ‘Hash.new {|h, key| h[key] = some_calculated_value }’, don’t worry worry about the result of the block being nil or false + mazingly, Hash works just fine with keys that are actually arrays.
  4. use gems
    So if you’re working on an app that needs a lot of memoization, you might want to use a gem that handles memoization for you with a nice, friendly API. Memoist

https://www.justinweiss.com/articles/4-simple-memoization-patterns-in-ruby-and-one-gem/

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

begin…end

A

The begin…end creates a block of code in Ruby that can be treated as a single thing, kind of like {…} in C-style languages. That’s why ||= works just as well here as it did before.