Why do we need to use a hash in front of curly braces?


I was trying to understand why we need the hash in front of the curly braces. Does anyone know?

friends.each { |x| puts "#{x}" }


What do you mean by that?

The each method is used to scan through an array or a hash, and the each method takes a block as an argument, that's why we use {}, but you can also use do...end instead if you prefer.


In C language, # stands for preprocessor before execution the statements. Likewise, While the programs execute, the value of x is also stored as variable(depends on user's definition, static or volatile).



OH! THESE curly braces. I didn't answer properly then ^^.


In Ruby, the way string interpolation is done is using the above syntax. Other languages, like Swift, for example, use a different syntax:


It is only a matter of convention and standard notation for the programming language.

String interpolation takes whatever is stored in the variable and displays that value.

x = 4
puts "The value stored in the variable x is #{x}"


The value stored in the variable x is 4

By the way, the pound sign ("hash" #) just explained has nothing to do with the Hash data structure, which is an associative array (also called dictionary, for people who know Python) that maps a key to a value.