Method declaration with def in Ruby - Time & Space Complexity
When we declare a method using def in Ruby, it is important to understand how the time it takes to run grows as the method does more work.
We want to know how the number of steps changes when the method handles bigger inputs.
Analyze the time complexity of the following code snippet.
def greet(names)
names.each do |name|
puts "Hello, #{name}!"
end
end
names_list = ["Alice", "Bob", "Charlie"]
greet(names_list)
This method takes a list of names and prints a greeting for each name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each name in the list with
each. - How many times: Once for every name in the list.
As the list of names gets bigger, the method runs the greeting for each name.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greetings printed |
| 100 | 100 greetings printed |
| 1000 | 1000 greetings printed |
Pattern observation: The number of greetings grows directly with the number of names.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of names.
[X] Wrong: "Declaring a method with def always takes constant time no matter what happens inside."
[OK] Correct: The time depends on what the method does. If it loops over input, the time grows with input size.
Understanding how method declarations relate to time helps you explain how your code behaves as inputs grow, a key skill in programming.
"What if the method called another method inside the loop? How would the time complexity change?"
Practice
Solution
Step 1: Understand Ruby method syntax
In Ruby, methods start with the keyworddefand end withend.Step 2: Identify the correct keyword
The correct keyword to start a method isdef, notfunction,method, ordefine.Final Answer:
def -> Option DQuick Check:
Method start keyword = def [OK]
- Using 'function' like in JavaScript
- Using 'method' keyword which doesn't exist
- Forgetting to use 'def' to start method
greet in Ruby?Solution
Step 1: Check Ruby method syntax
Ruby methods start withdef method_name()and end withend. Parentheses are optional but allowed.Step 2: Identify correct syntax
def greet() puts "Hello" end usesdef greet() puts "Hello" end, which is correct Ruby syntax. Options B and D use wrong keywords, and C missesend.Final Answer:
def greet() puts "Hello" end -> Option CQuick Check:
Correct Ruby method syntax = def greet() puts "Hello" end [OK]
- Forgetting the 'end' keyword
- Using JavaScript style 'function' keyword
- Missing parentheses or using wrong keywords
def add(a, b) a + b end puts add(3, 4)
Solution
Step 1: Understand method parameters and return
The methodaddtakes two parametersaandband returns their suma + b.Step 2: Calculate the method call result
Callingadd(3, 4)returns 3 + 4 = 7, which is printed byputs.Final Answer:
7 -> Option AQuick Check:
3 + 4 = 7 [OK]
- Thinking it concatenates as strings
- Expecting explicit return keyword
- Confusing output with code text
def say_hello puts "Hello"
Solution
Step 1: Check method structure
Ruby methods must start withdefand end withend. This code misses theendkeyword.Step 2: Identify the missing part
Withoutend, Ruby will raise a syntax error because the method is not properly closed.Final Answer:
Missing 'end' keyword to close method -> Option AQuick Check:
Every method needs 'end' [OK]
- Forgetting 'end' after method body
- Thinking parentheses are mandatory
- Assuming underscores are invalid in names
greet_person that takes a name and returns a greeting like "Hello, Alice!". Which code correctly does this?Solution
Step 1: Understand method return vs output
To return a greeting string, the method should produce the string as its last expression or usereturn. Usingputsorprintoutputs to console but returns nil.Step 2: Analyze each option
def greet_person(name) "Hello, " + name + "!" end returns the greeting string correctly. def greet_person(name) puts "Hello, #{name}!" end prints but returns nil. def greet_person(name) return puts "Hello, " + name + "!" end returns nil becauseputsreturns nil. def greet_person(name) print "Hello, " + name + "!" end prints but does not return the string.Final Answer:
def greet_person(name) "Hello, " + name + "!" end -> Option BQuick Check:
Return string, not print it [OK]
- Using puts instead of returning string
- Returning result of puts (which is nil)
- Confusing print with return
Ready to prove it?
Pass the test and this pattern moves unknown
