How to Use the Ruby store Method

09/24/2021

Contents

In this article, you will learn how to use the Ruby store method.

Using the store method

The store method is a built-in Ruby method that is used to add or update the key-value pairs of a hash. It can be used to create new keys or update the values of existing keys in a hash.

Syntax

The syntax for the store method is as follows:

hash.store(key, value)

Parameters

  • hash: The hash in which the key-value pair is to be added or updated.
  • key: The key to be added or updated.
  • value: The value to be associated with the key.

Examples

For example, let’s say we have a hash named my_hash and we want to add a new key-value pair to it. We can use the store method as follows:

my_hash = {}
my_hash.store(:name, "John")

This will create a new key-value pair in my_hash, where :name is the key and “John” is the value associated with it.

If the key already exists in the hash, the store method will update the value associated with it. For example:

my_hash = {name: "John"}
my_hash.store(:name, "Jane")

This will update the value associated with the key :name in my_hash from “John” to “Jane”.

In addition to the store method, there are other methods that can be used to add or update key-value pairs in a hash. For example, the [] method can also be used to add or update key-value pairs. The difference between the two methods is that [] can also be used to access the value associated with a key, whereas store is used only to add or update key-value pairs.