Intern
What are parentheses in the Ruby programming language?
sobes.tech AI
Answer from AI
Parentheses in Ruby can be used for different purposes depending on the context:
- Calling a method with arguments.
method_name(argument1, argument2) - Accessing an element of an array or hash.
array[index],hash[key] - Defining an array or hash.
[element1, element2],{key1 => value1, key2 => value2} - Grouping expressions to change the order of execution.
(expression1 + expression2) * 3 - Defining code blocks (for single lines). Although for multi-line blocks,
do...endis more common, parentheses()can also be used.array.each { |item| puts item }
# Calling a method with arguments
puts("Hello, world!")
# Accessing an array element
my_array = [1, 2, 3]
puts my_array[1] # Will output 2
# Accessing a hash element
my_hash = { "a" => 1, "b" => 2 }
puts my_hash["a"] # Will output 1
# Defining an array
another_array = [4, 5, 6]
# Defining a hash
another_hash = { "c" => 3, "d" => 4 }
# Grouping expressions
result = (5 + 3) * 2 # The result will be 16, not 11
# Code block (single line)
[1, 2, 3].each { |n| puts n * 2 }