Ruby: Programming Languages Flashcards
What does the self
keyword represent in Ruby & how is it used?
In Ruby, self is a special keyword used to refer to the current object or the instance of the class within the context where it is called. Its usage helps distinguish between instance variables and local variables and allows you to call other methods within the same instance without explicitly specifying the instance’s name.
How does Ruby handle multiple inheritance?
Ruby does not support multiple inheritance directly through classes (unlike some other languages where a class can inherit from multiple classes).
Instead, Ruby uses a feature called “mixins” through modules to achieve the functionality of multiple inheritance.
Modules in Ruby can define methods and be included in classes.
When a module is included in a class, the class can use the methods defined in the module.
What is inheritance in Ruby?
Inheritance in Ruby allows a class (the child or subclass) to inherit features (methods and attributes) from another class (the parent or superclass).
It’s a way to establish a subtype from an existing class.
Inheritance models a “is a” relationship between two classes.
How is Inheritance Implemented in Ruby?
Inheritance is implemented by using the < symbol in the class definition.
The class that is inheriting the features is called the subclass, and the class whose features are being inherited is called the superclass.
What is Metaprogramming in Ruby?
Metaprogramming in Ruby refers to the concept of writing code that can manipulate, create, or alter code at runtime.
This allows programs to be more flexible and dynamic.
Ruby provides several metaprogramming capabilities, allowing developers to create methods on the fly, alter the behavior of classes and objects, and dynamically evaluate code.
What is Dynamic Method Creation in Ruby?
Dynamic method creation in Ruby allows programmers to define methods at runtime. This feature provides flexibility, enabling classes to generate methods on the fly based on dynamic data or program state.
This can be achieved using define_method, which is a method of the Module class, allowing for the addition of new methods to classes or modules during runtime.
What is Dynamic Dispatch in Ruby?
Dynamic dispatch in Ruby is a mechanism that determines which method to call at runtime based on the object’s type or class.
It allows Ruby to be highly flexible and dynamic, supporting polymorphism and method overriding.
Instead of determining the method call at compile time, Ruby resolves the method during execution, deciding which implementation to invoke based on the receiver’s actual class.
What does the “prepend” keyword do in Ruby classes?
In Ruby, prepend
is a keyword used within a class to include a module such that the module’s methods are added to the beginning of the class’s method lookup chain.
This means that the module’s methods will override the class’s methods if they have the same name. It’s a powerful feature for modifying class behavior without altering the class code directly.
How do you assign the value 10 to a variable namedscorein Ruby?
score = 10
Ruby has several basic data types. Can you name at least three of them?
String, Integer, Array, Float, Array, Hash, Symbol, Nil, Range, Regexp
Given two variables,name = “Alice”andage = 30, how would you use string interpolation to print “Alice is 30 years old” in Ruby?
name = “Alice”
age = 30
puts “#{name} is #{age} years old”
How do you create an array containing the numbers 1, 2, and 3 in Ruby?
array = [1, 2, 3]
How do you create a hash in Ruby with keys:nameand:age, and corresponding values”Bob”and25?
person = { name: “Bob”, age: 25 }
How do you write awhileloop in Ruby that prints numbers from 1 to 5?
number = 1
while number <= 5
puts number
number += 1
end
How do you define a simple method in Ruby that takes a name as an argument and prints “Hello, [name]!”?
def greet(name)
puts “Hello, #{name}!”
end
What is the main difference between symbols and strings in Ruby?
Immutability: Symbols are immutable, meaning they cannot be modified after they are created. In contrast, strings are mutable and can be altered any time.Identity: Symbols of the same name are identical at the object level. When you reference a symbol multiple times, each reference points to the same object in memory. However, each time you create a string, even if it contains identical text, Ruby creates a new object in memory.
How do you iterate over an array[1, 2, 3]and print each element in Ruby?
[1, 2, 3].each do |element|
puts element
end
What are the different types of loops available in Ruby?
while Loop: Repeats code while a condition is true.
until Loop: Executes code until a condition is true.
for Loop: Iterates over a range or collection.
each Loop: Iterates over elements of an enumerable (preferred).
times Loop: Executes a block a specific number of times.
loop Method: Infinite loop, use break to exit.
How do you write a simpleforloop in Ruby to print numbers 1 through 5?
To write a simple for loop in Ruby that prints numbers from 1 through 5, you can use the following syntax:
for i in 1..5
puts i
end
This loop uses a range (1..5) to iterate from 1 to 5, inclusive.
The variable i takes on each value in the range, one at a time, and the puts command inside the loop prints each value to the console.
What is aneachloop, and how does it differ from aforloop in Ruby?
In Ruby, the each
loop and the for
loop both serve the purpose of iterating over elements in a collection, but they do so in slightly different ways with differing implications for style and scope.
The each
loop is more idiomatic to Ruby and is commonly used to iterate over elements in an enumerable, like arrays, hashes, and ranges. It passes each element of the collection to the block of code enclosed by the {}
or do...end
.
Example:
```ruby
[1, 2, 3, 4, 5].each do |number|
puts number
end
~~~
-
Scope of Variables:
- In a
for
loop, the loop variable (e.g.,number
infor number in [1,2,3,4,5]
) remains defined after the loop completes. - In contrast, variables defined within an
each
block are scoped to the block itself; any new variables introduced in the block do not exist outside of it.
- In a
-
Idiomatic Ruby:
- The
each
loop is preferred in Ruby because it fits better with Ruby’s object-oriented nature.each
is a method called on a collection object, emphasizing operating on objects through methods rather than using external control structures.
- The
-
Performance:
- There’s generally not a significant performance difference, but the
each
method may provide better encapsulation and is less prone to side effects due to variable scoping.
- There’s generally not a significant performance difference, but the
Example with for
for comparison:
```ruby
for number in [1, 2, 3, 4, 5]
puts number
end
# Variable ‘number’ is still accessible here
~~~
While both loops can achieve similar outcomes, the each
loop is favored for its alignment with Ruby’s design philosophy of clear, concise, and safe code, primarily due to how it handles variable scope and its use as a method on objects rather than a control structure.
How can you exit a loop prematurely in Ruby?
In Ruby, you can exit a loop prematurely using several control flow mechanisms depending on the context and the specific behavior you need:
-
break
: This is used to exit a loop immediately, stopping all further iterations. It’s the most straightforward way to break out of a loop prematurely.ruby loop do puts "This will print only once." break end
-
next
: Instead of exiting the loop entirely,next
skips the remainder of the current iteration and proceeds directly to the next iteration. It’s useful for skipping over certain values or conditions without stopping the entire loop.ruby (1..5).each do |x| next if x == 3 puts x end # Outputs: 1, 2, 4, 5
-
return
: If you are within a method and need to exit not only the loop but also the method itself,return
can be used. This will end the method execution and optionally return a value.```ruby
def print_numbers
(1..10).each do |x|
return x if x > 5 # Returns the first number greater than 5
end
endputs print_numbers # Outputs: 6
``` -
redo
: While not exactly a way to exit a loop,redo
is useful for repeating the current iteration of the loop from the beginning without re-evaluating the loop condition or moving to the next element. This is rarely used but can be helpful in specific scenarios where an iteration may need to be retried due to an error or a missed condition.ruby (1..3).each do |x| puts x redo if x == 3 # This will create an infinite loop printing '3' end
These control flow mechanisms provide powerful ways to handle complex looping scenarios in Ruby, allowing you to precisely control how and when loops should end or continue.
Explain what anuntilloop does in Ruby. How is it different from awhileloop in terms of its condition?
The until
loop in Ruby is a control structure used to repeatedly execute a block of code as long as a specified condition remains false. It’s essentially the opposite of a while
loop, which runs as long as the condition is true. The until
loop continues to run until the condition becomes true, and then it stops.
```ruby
until condition
# code to execute
end
~~~
Here, the code inside the loop executes repeatedly until the condition
evaluates to true. If the condition
starts out as true, the code inside the loop will not execute even once.
To understand the difference, it helps to see both loops in action. Here’s how you can use both while
and until
loops to perform the same task with opposite conditions:
```ruby
x = 0
while x < 5
puts x
x += 1
end
# Prints 0, 1, 2, 3, 4
~~~
```ruby
x = 0
until x >= 5
puts x
x += 1
end
# Also prints 0, 1, 2, 3, 4
~~~
-
Condition Handling: The
while
loop runs as long as the condition is true. In contrast, theuntil
loop runs as long as the condition is false. -
Usage: You typically use a
while
loop when you want to continue looping while something is true (e.g., while there is more data to process). On the other hand, anuntil
loop is more suitable when you need to keep looping until something becomes true (e.g., until a process completes or an error occurs). -
Readability: The choice between using a
while
or anuntil
loop can often come down to what makes your code more readable. Choosing the one that fits the context of your condition naturally can make your code easier to understand.
The decision to use until
versus while
often depends on which approach makes the logic of your condition clearer in the context of what the code is intended to achieve.
Explain what anuntilloop does in Ruby. How is it different from awhileloop in terms of its condition?
The until
loop in Ruby is a control structure used to repeatedly execute a block of code as long as a specified condition remains false. It’s essentially the opposite of a while
loop, which runs as long as the condition is true. The until
loop continues to run until the condition becomes true, and then it stops.
```ruby
until condition
# code to execute
end
~~~
Here, the code inside the loop executes repeatedly until the condition
evaluates to true. If the condition
starts out as true, the code inside the loop will not execute even once.
To understand the difference, it helps to see both loops in action. Here’s how you can use both while
and until
loops to perform the same task with opposite conditions:
```ruby
x = 0
while x < 5
puts x
x += 1
end
# Prints 0, 1, 2, 3, 4
~~~
```ruby
x = 0
until x >= 5
puts x
x += 1
end
# Also prints 0, 1, 2, 3, 4
~~~
-
Condition Handling: The
while
loop runs as long as the condition is true. In contrast, theuntil
loop runs as long as the condition is false. -
Usage: You typically use a
while
loop when you want to continue looping while something is true (e.g., while there is more data to process). On the other hand, anuntil
loop is more suitable when you need to keep looping until something becomes true (e.g., until a process completes or an error occurs). -
Readability: The choice between using a
while
or anuntil
loop can often come down to what makes your code more readable. Choosing the one that fits the context of your condition naturally can make your code easier to understand.
The decision to use until
versus while
often depends on which approach makes the logic of your condition clearer in the context of what the code is intended to achieve.
How would you use a loop to create an array containing the squares of numbers 1 through 5?
To create an array containing the squares of numbers 1 through 5 in Ruby, you can use several approaches. Here’s one using the each
loop, which is very idiomatic in Ruby, and another using the map
method which is even more succinct and idiomatic for this specific use case.
You can initialize an empty array and then use an each
loop to iterate through the numbers 1 to 5, append the square of each number to the array.
```ruby
squares = []
(1..5).each do |number|
squares «_space;number ** 2
end
puts squares # Output: [1, 4, 9, 16, 25]
~~~
A more Ruby-esque way to do this would be to use the map
method, which applies a given block of code to each element of a collection and returns a new array containing the results.
```ruby
squares = (1..5).map { |number| number ** 2 }
puts squares # Output: [1, 4, 9, 16, 25]
~~~
Both of these methods will give you an array [1, 4, 9, 16, 25]
, but the map
method is generally preferred for this type of operation because it directly expresses the intention of transforming a list of values into a new list of transformed values, keeping the code concise and clear.