OneBite.Dev - Coding blog in a bite size

loop object in Ruby

Code snippet on how to loop object in Ruby

  object = { name: "John", age: 20}
 
  object.each do |key, value| 
    puts "#{key}: #{value}"
end

The code above is looping through an object in Ruby. The object has two keys: “name” and “age”. To start the loop, the variable ‘object’ is created, and the two keys, “name” and “age”, with their values, are stored in the variable.

This is followed by the ‘each do’ loop. The syntax for the loop takes two variables, ‘key’ and ‘value’, as parameters. ‘key’ represents the keys from the object and ‘value’ represents the values. Then, the code to be executed is included in the do and end block. In this case, it is a puts statement, which will print the key and value on the screen.

Finally, the end keyword closes the loop, and the code will loop through each key and value pair of the object. After the loop is complete, the output will be: “name: John” and “age: 20”.

ruby