Ruby Flashcards
Bloks
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.
IMPLICIT BLOCKS AND THE yield KEYWORD
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
EXPLICITLY PASSING BLOCKS
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.
Proc
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}!” }
&:
[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.
lambdas
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.
.to_s
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”
.count
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
.select vv .reject
def friend(friends) friends.select { |name| name.length == 4 } end
def friend(friends) friends.reject { |name| name.length != 4 } end
memoization
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.
- using the conditional assignment operator: ||=
When should you memoize?
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`)
Garbage Collection
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.
What is method_missing?
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, &block) puts "There's no method called #{m} here -- please try again." end
Ruby modules
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.
4 Simple Memoization Patterns in Ruby (And One Gem)
- Super basic memoization ‘||=’
- multi-lines ‘ || = begin … end’
note!: nil, false. use ‘if defined?’ - 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. - 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/