Ruby Programming
103 flashcards by MentisLibrary
Ruby the way Rubyists write it: truthiness and symbols, strings and collections, blocks, procs and lambdas, classes, modules and mixins, metaprogramming, exceptions, and the gem and Bundler tooling.
- Which values are falsy in Ruby?
- Only false and nil. Everything else is truthy, including 0, "", [] and {}.
- What does it mean that everything in Ruby is an object?
- Every value, including nil, integers, symbols and classes themselves, responds to methods. There are no primitive types outside the object model.
- What distinguishes a symbol from a string?
- A symbol such as :name is an immutable, interned identifier: every occurrence is the same object. A string is mutable and each literal creates a new object.
- How does Ruby distinguish local, instance, class and global variables?
- By sigil: a bare lowercase name is local, @name is an instance variable, @@name a class variable, $name a global, and a Capitalized name is a constant.
- What does an unset instance variable evaluate to?
- nil. Instance variables are never declared, so a typo produces nil instead of an error.
- What do a trailing ? and ! on a method name mean?
- Conventions, not syntax. ? marks a predicate returning true or false; ! marks the more surprising or destructive of a pair of methods.
- What does a Ruby method return when there is no return?
- The value of the last expression evaluated. Explicit return is used mainly for early exit.
- puts versus print versus p
- puts writes to_s plus a newline and flattens arrays onto separate lines. print writes to_s with no newline. p writes inspect plus a newline and RETURNS its argument.
- How does string interpolation work?
- "#{expression}" evaluates the expression, calls to_s on the result and splices it in. It works only in double-quoted strings, heredocs and %W.
- What is the difference between && and and?
- They compute the same thing but and has much lower precedence, below assignment. && binds tighter than =, and does not.
- What does ||= do?
- Assigns the right side only when the left side is nil or false. It expands roughly to x || x = value.
- How do 1..5 and 1...5 differ?
- Two dots include the end value, three dots exclude it. Both build a Range, which is enumerable and usable in case.
- What comparison does case/when actually use?
- The case equality operator === on the when value, so a Range tests inclusion, a Regexp tests a match, a Class tests is_a?, and a lambda is called.
- What does the safe navigation operator &. do?
- Calls the method only if the receiver is not nil; otherwise the whole expression is nil.
- How do you write a guard clause, and why?
- Return, raise or next at the top of the method for the cases you will not handle, so the main path is never indented.
- When is unless the right choice?
- For a single negative condition where if ! would read worse. Never with else, and never with a compound condition.
- What does the ternary and the then keyword offer?
- cond ? a : b for a short two-way choice. then is optional after if/when and lets a branch sit on one line.
- How does integer division behave, and how do you get a float?
- / between two integers truncates toward negative infinity. Use fdiv, or make one operand a float.
- What size can a Ruby integer reach?
- Any size. Integer is arbitrary precision and grows beyond machine word size automatically.
- How do multiple assignment and the splat operator work?
- The left side is matched positionally; *name absorbs the remaining values into an array. It works in assignment, in block parameters and in method parameters.
- How do keyword arguments differ from a trailing options hash?
- Keyword arguments are declared by name with name:, are checked at call time, and are kept separate from positional arguments. A hash passed positionally is no longer converted into them.
- What do *args, **opts and &blk collect in a method signature?
- *args gathers extra positional arguments into an array, **opts gathers keyword arguments into a hash, and &blk captures the block as a Proc.
- Single quotes versus double quotes in Ruby
- Double quotes interpolate #{} and process escapes such as \n. Single quotes handle only \\ and \'.
- What do %w, %i and %q build?
- %w[a b c] an array of strings, %i[a b c] an array of symbols, %q() a single-quoted string and %Q() a double-quoted one.
- What does the squiggly heredoc <<~ do?
- Removes the common leading indentation from every line, so a multi-line string can be indented with the surrounding code.
- How do String#+ and String#<< differ?
- + returns a new string and leaves both operands alone. << appends in place and returns the same object, mutating anything else holding a reference.
- What does the # frozen_string_literal: true magic comment do?
- Makes every string literal in that file frozen, so attempts to mutate one raise FrozenError and identical literals can be shared.
- How does gsub differ from sub, and what can the replacement be?
- sub replaces the first match, gsub every match. The replacement can be a string with \1 backreferences, a hash, or a block receiving the match.
- How do you test whether a string matches a pattern?
- Regexp#match? or String#match? returns a boolean and sets no globals, which makes it the fast, side-effect-free choice.
- How do named captures work in a Ruby regex?
- (?<name>...) labels a group. MatchData#[] accepts the name, and =~ against a LITERAL regex also assigns local variables.