Join my Laravel for REST API's course on Udemy 👀

Add item to hash in Ruby

August 17, 2022  ‐ 1 min read

In order to add items to a hash in Ruby we most commonly use the square bracket notation ([ ]). Which associates the given key with the value in the hash. Do keep in mind that we use the same method to update the value of existing key in the hash.

hash = {
  python: 'Django',
  php: 'Laravel',
  ruby: 'Ruby on Rails',
}

hash[:javascript] = 'Express'

But we have other options as well, we could for example use the merge method. Or the .store() method that is actually an alias for the square bracket notation.

hash = {
  python: 'Django',
  php: 'Laravel',
  ruby: 'Ruby on Rails',
}

hash.store(:javascript, 'Express')