Ruby Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q
hours = 2
minutes = 3

How would you format this to “hh:mm” format?

A

“%02d:%02d” % [hours, minutes]

or

format(‘%02d:%02d’, hours, minutes)

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

How would you round the float: 45.32423234 to 3 decimal places and display result as a string?

A

num = 45.32423234.round(3)
puts “The result is #{num}”

or

“The result is %0.3f” % num
or
format(“%0.3f”, num)

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

What will be the output?

str = “a string”

def str
“a method”
end

p str

A

“a string”

To invoke the method instead, add parenthesis:

p str()

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

What will be the output?

def method(param)
param = param + “world”
param &laquo_space;“universe”
end

str = “hello”

method(str)

p str

A

“hello”

# a = 'hello'
# b = a + ' world'
# b << ' universe' => b = 'hello world universe'
# puts a => 'hello'
# a is unaffected
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What will this print?

def method(str)
str += ‘WORLD’
end

str = “hello”

method(str)

p str

A

“hello”

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

What is the return value of:

# 1. 
'hello'.delete('o')
# 2.
[1, 2, 3, 4, 5].delete(4)
A
  1. “hell”

2. 4

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

What is ‘truthiness’? What is considered to be ‘truthy’ in Ruby?

A

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

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

What are the benefits of using Object Oriented Programming in Ruby? Think of as many as you can.

A
  1. Creating objects allow programmers to think more abstractly about the code they are writing.
  2. Objects are represented by nouns so are easier to conceptualize.
  3. It allows us to only expose functionality to the parts of code that need it, meaning namespace issues are much harder to come across.
  4. It allows us to easily give functionality to different parts of an application without duplication.
  5. We can build applications faster as we can reuse pre-written code.
  6. As the software becomes more complex this complexity can be more easily managed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Describe the difference between declarative and imperative methods/programming.

A

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.

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

Should I reach for an instance variable directly or use getter/setter methods?

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is one of the biggest benefits of Object Oriented Programming over procedural?

A

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:

  1. 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.
  2. Information-hiding: By interacting only with an object’s methods, the details of its internal implementation remain hidden from the outside world.
  3. 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.
  4. 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the main difference between private and protected methods?

A

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.

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

Should I mix in a module or implement inheritance?

A

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.

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

Give some examples of when you would use a Set instead of an Array

A
  • 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

You execute this code:

echo(“hello!”)

and get a LocalJumpError. What is going on here?

A

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.

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

What is ‘arity’?

A

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.

17
Q

What is a “Test Suite”?

What is a “test”?

What is an “assertion”?

A

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.

18
Q

What is a “DSL”?

A

DSL refers to Domain Specific Language.

19
Q

What are the steps to writing a test

A

Use SEAT approach:

  1. set up necessary objects
  2. execute code against the object we are testing
  3. assert results of execution
  4. tear down and clean up any lingering artifacts
20
Q

What is ‘code coverage’ and what does it mean to have 100% code coverage?

A

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.

21
Q

What is a closure?

A

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.

22
Q

Describe how the Kernel method #block_given? is used?

A

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.

23
Q

What is the difference between blocks, procs and lamdas in terms of their arity rules

A

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.

24
Q

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

A

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.

25
Q

What is the difference between blocks, procs and lamdas in terms of their behaviour when returning from each one?

A

When the proc is defined in the method, then called, we immediately exit (or return) from the method:

def check_return_with_proc
  my_proc = proc { return }
  my_proc.call
  puts "This will never output to screen."
end

If it was a lambda, block would be executed but execution would continue to the next line.

If lambda is defined outside of the method, execution will continue after the call:

my_lambda = lambda { return }
def check_return_with_lambda(my_lambda)
  my_lambda.call
  puts "This will be output to screen."
end

If same as above but with proc, an error will be thrown because execution will jump to where proc is defined and we cannot return from the top level of a program.

26
Q

What is a ‘system Ruby’?

A

Your system Ruby is a complete installation of Ruby and its standard components. Usually /usr/bin/ruby on a Mac. If you see that you are using a system Ruby, you should install a Ruby version manager since system Ruby is not suitable for development.

27
Q

What is the primary concern of the commonly used gem “Bundler”?

A

Bundler is used to manage the Gem dependencies of your projects. That is, it determines and controls the Ruby version and Gems that your project uses, and attempts to ensure that the proper items are installed and used when you run the program.

28
Q

What is a constructor?

A

A constructor refers to the initialize method when a new object is instantiated from a given Class. The initialize method is automatically run when a new instance of a class is created “constructing” all the attributes of the object.

29
Q

What is a ‘data in/data out’ or ‘pure’ function?

A

In general programming terms, it’s a function or method that has all the information it needs - provided by user in form of arguments to a method. Data is passed in by the user to the method and returns something without having to rely on state of an object or another method. Everything the method needs is contained within it or arguments that are passed in.

30
Q

Describe how yielding to a block and calling a method are similar

A

Yielding to a block is like calling an unnamed method in Ruby. You can yield with arguments just like you can pass in arguments to method calls but a block won’t care if you pass the ‘wrong’ number of arguments.

Just like a method’s return value, the return value of yielding to a block can be saved in a variable for later use.

31
Q

How do you define an alias method in Ruby?

A

def <, :

32
Q

In regex, what is considered a word character

A

Word characters consist of any alpha characters a-zA-Z, all decimal digits 0-9 and an underscore (_).

33
Q

In regex, /./ matches every character except…

A

newline characters