Ruby Flashcards
hours = 2 minutes = 3
How would you format this to “hh:mm” format?
“%02d:%02d” % [hours, minutes]
or
format(‘%02d:%02d’, hours, minutes)
How would you round the float: 45.32423234 to 3 decimal places and display result as a string?
num = 45.32423234.round(3)
puts “The result is #{num}”
or
“The result is %0.3f” % num
or
format(“%0.3f”, num)
What will be the output?
str = “a string”
def str
“a method”
end
p str
“a string”
To invoke the method instead, add parenthesis:
p str()
What will be the output?
def method(param)
param = param + “world”
param «_space;“universe”
end
str = “hello”
method(str)
p str
“hello”
# a = 'hello' # b = a + ' world' # b << ' universe' => b = 'hello world universe'
# puts a => 'hello' # a is unaffected
What will this print?
def method(str)
str += ‘WORLD’
end
str = “hello”
method(str)
p str
“hello”
What is the return value of:
# 1. 'hello'.delete('o') # 2. [1, 2, 3, 4, 5].delete(4)
- “hell”
2. 4
What is ‘truthiness’? What is considered to be ‘truthy’ in Ruby?
In Ruby, everything that is not ‘nil’ or ‘false’ or does not return ‘nil’ or ‘false’ is considered to be ‘truthy’ and is considered true.
Considered true is not the same thing as true object.
num = 5 # truthy and considered true, but;
true == num # => false
What are the benefits of using Object Oriented Programming in Ruby? Think of as many as you can.
- Creating objects allow programmers to think more abstractly about the code they are writing.
- Objects are represented by nouns so are easier to conceptualize.
- It allows us to only expose functionality to the parts of code that need it, meaning namespace issues are much harder to come across.
- It allows us to easily give functionality to different parts of an application without duplication.
- We can build applications faster as we can reuse pre-written code.
- As the software becomes more complex this complexity can be more easily managed.
Describe the difference between declarative and imperative methods/programming.
In computer science, declarative programming is a programming paradigm—a style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow.[1]
In computer science, imperative programming is a programming paradigm that uses statements that change a program’s state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program consists of commands for the computer to perform. Imperative programming focuses on describing how a program operates.
The term is often used in contrast to declarative programming, which focuses on what the program should accomplish (high level commands like “display board”, “player moves”) without specifying how the program should achieve the result.
Should I reach for an instance variable directly or use getter/setter methods?
Typically use getter/setter methods if your class has them.
Avoid when:
- those methods do some pre or post processing, and you wish to only work with the raw data in the instance variable.
- If your objects do not need to expose their internal instance variables to the outside, then you don’t need getter or setter methods at all. Note: this is only talking about referencing instance variables in the same class; this is not talking about reaching into an object from the outside and accessing or modifying its instance variables.
What is one of the biggest benefits of Object Oriented Programming over procedural?
Modifying an OOP program is easier/safer because changes are encapsulated to a class or object.
OOP proramming forces you to set up more indirection but that indirection gives us an opportunity to isolate concerns so they don’t ripple across the entire codebase.
- The interface methods to collaborate with a class or object can remain the same while the implementation changes.
BENEFITS OF OOP:
- Modularity: The source code for a class can be written and maintained independently of the source code for other classes. Once created, an object can be easily passed around inside the system.
- Information-hiding: By interacting only with an object’s methods, the details of its internal implementation remain hidden from the outside world.
- Code re-use: If a class already exists, you can use objects from that class in your program. This allows programmers to implement/test/debug complex, task-specific objects, which you can then use in your own code.
- Easy Debugging: If a particular object turns out to be a problem, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.
What is the main difference between private and protected methods?
The main difference between them is protected methods allow access between class instances, while private methods don’t.
When a method is private, only the class - not instances of the class - can access it(cannot be called with an explicit receiver). However, when a method is protected, only instances of the class or a subclass can call the method. This means we can easily share sensitive data between instances of the same class type.
Should I mix in a module or implement inheritance?
You can only subclass from one class. But you can mix in as many modules as you’d like.
If it’s an “is-a” relationship, choose class inheritance. If it’s a “has-a” relationship, choose modules. Example: a dog “is an” animal; a dog “has an” ability to swim.
You want additional functionality? - Module
Extend abilities of a class? - Inheritance (coincides with ‘is-a’ relationship)
You cannot instantiate modules (i.e., no object can be created from a module) Modules are used only for namespacing and grouping common methods together.
Give some examples of when you would use a Set instead of an Array
- Creating sequences that cannot have duplicates.
- Creating sequences where the order of elements doesn’t matter.
- Creating sequences that need to be compared for equality regardless of order.
You execute this code:
echo(“hello!”)
and get a LocalJumpError. What is going on here?
It means that the method implementation for the ‘echo’ method has a ‘yield’ in it somewhere. It is expecting a block, but no block was provided.
What is ‘arity’?
Rules around enforcing the number of arguments you can call on a closure in Ruby is called its arity.
In Ruby, blocks have lenient arity rules. Procs and lambdas have different arity rules.
What is a “Test Suite”?
What is a “test”?
What is an “assertion”?
Refers to all tests that accompany your program or application
A test describes a situation or context in which tests are run. For example, a test can be to verify that an error message is displayed when an incorrect password is entered.
An assertion is the actual verification step in a test to confirm that the data returned by your program is indeed what is expected.
What is a “DSL”?
DSL refers to Domain Specific Language.
What are the steps to writing a test
Use SEAT approach:
- set up necessary objects
- execute code against the object we are testing
- assert results of execution
- tear down and clean up any lingering artifacts
What is ‘code coverage’ and what does it mean to have 100% code coverage?
code coverage refers to how much of our actual code is tested by a test suite.
100% code coverage means that we have some tests in place for every method. It has nothing to say about the ‘quality’ of those tests or whether the tests cover every edge case or if the program is running correctly.
What is a closure?
A closure is a general programming concept that allows programmers to save a “chunk of code” and execute it at a later time. It’s called a “closure” because it’s said to bind its surrounding artifacts (ie, variables, methods, objects, etc) and build an “enclosure” around everything so that they can be referenced when the closure is later executed.
also called ‘anonymous functions’ in some languages.
Describe how the Kernel method #block_given? is used?
It is used to detect if a block has been passed into a method at its invocation or not.
Most common use is to wrap the yield call in a conditional. if a block is given, yield to the block and if ‘block_given?’ is false then do something else.
What is the difference between blocks, procs and lamdas in terms of their arity rules
blocks, procs and lambdas have different arity rules.
Lambdas enforce the number of arguments passed to them. Implicit block and Procs do not enforce the number of arguments passed in.
lamda is less “forgiving” in its arity - if no argument is passed to a lamda where a block requires a parameter an ArgumentError will be thrown.
What is the output of code below and why?
def block_method_2(animal) yield(animal) end
block_method_2(‘turtle’) do |turtle, seal|
puts “This is a #{turtle} and a #{seal}.”
end
If we pass too few arguments to the block, the remaining block variables are assigned a value of ‘nil’
Therefore we would get: “This is a turtle and a .” as our output.
In the same way, if we pass NO arguments but the block takes one or more, ‘nil’ is assigned to the block variable(s) and the block still executes.