Junior
What are curly braces in the Ruby programming language?
sobes.tech AI
Answer from AI
Curly braces {} in Ruby are used in several contexts:
-
Defining code blocks (blocks):
- For single-line blocks or when the block contains little code.
# Example of using a block with the `each` method [1, 2, 3].each { |n| puts n * 2 } # Example of using a block with the `map` method doubled_numbers = [1, 2, 3].map { |n| n * 2 } -
Defining hashes (Hashes):
- For creating hash literals.
# Example of creating a hash with symbols as keys user = { name: "Alice", age: 30 } # Example of creating a hash with different key types settings = { "theme" => "dark", :notifications => true, 1 => "value" } -
Nested data structures:
- Along with square brackets
[]for creating nested arrays and hashes.
# Example of a nested hash in an array data = [{ id: 1, value: "A" }, { id: 2, value: "B" }] # Example of a nested array in a hash config = { users: ["Alice", "Bob"], roles: ["admin", "user"] } - Along with square brackets