2 Ruby basics Flashcards
What standard Ruby classes do you know? What useful methods have you learned for each class?
- String (.new, interpolation, concatenation .capitalize, .downcase, .chars, .index(), .insert(), .match(), .partition(), .reverse, .split(‘ ‘))
- Array (.new, .at(), [], [..], .take(), .push, «, .unshift, .insert, pop, .delete_at(), .delete(), .length, .count, .size, .empty?, .any?, .include?(), .each, .each_index, .each_with_index, .map)
- Symbol (.object_id)
- Hash (.new, [], .delete, .delete_if, .shift, .each, .each_key, .each_value, .key?(), .value?(), .keys, .values, .values_at(), .length, .merge, .select, .dig)
- Integer and Float (.class)
- Range (.to_a)
- Time (.new(), .at(), .year, .month, .day, .wday, .yday, .hour, .min, .sec, .zone, .strftime())
What is the difference between .each and .map enumerable methods?
.each simply iterates over the given enumerable, running the block for each value. It discards the return value of the block, and each simply returns the original object it was called on.
.map, however, iterates over each element, using the return value of the block to populate a new array at each respective index and return that new array.
Neither each nor map themselves modify the original collection.
What is the difference between single and double quotes in the context of the string class?
Single quotes are more preferable. When we work with interpolation we must use double quotes.
What scope for variables do you know?
Local, Instance (@), Global ($), Constants (AN)
What is the difference between logical && and ’and’?
=> nil
one = :one
two = nil
t = one and two
# => nil
t
# => :one
t = one && two
# => nil
t
# => nil
t = (one and two)
# => nil
t
# => nil
(t = one) && two
# => nil
t
# => :one
What is the difference between procs and lambdas?
=> “Proc.new”
“return” inside procs makes code leave the block the proc is in.
def proc_return
Proc.new { return ‘Proc.new’ }.call
return ‘proc_return return’
end
def lambda_return
lambda { return ‘lambda’ }.call
return ‘lambda_return return’
end
proc_return
# => “Proc.new”
lambda_return
# => “lambda_return return”
How do you pass a block to a method? How do you ‘invoke’ that block in a certain place inside the method?
def try
if block_given?
yield
else
‘no block’
end
end
try
# => “no block”
try { ‘hello’ }
# => “hello”
try do ‘hello’ end
# => “hello”
or
def thrice
yield
yield
yield
end
x = 5
puts “value of x before: #{x}”
# => “value of x before: 5”
thrice { x += 1 }
puts “value of x after: #{x}”
# => “value of x after: 8”
What is the difference between methods with ’!’ and ‘?’ at the end of the name?
Methods with ‘!’ change given to method values after method work. ‘?’ means that method returns bool value.