0
0
Rubyprogramming~5 mins

Accessing and setting values in Ruby

Choose your learning style9 modes available
Introduction

We use accessing and setting values to get or change information stored in variables or data structures.

When you want to read a value stored in a variable or container.
When you need to update or change a value in a list or hash.
When you want to check what is inside a data structure before using it.
When you want to save new information into a variable or data structure.
When you want to keep track of changes in your program's data.
Syntax
Ruby
# Accessing a value
value = container[key]

# Setting a value
container[key] = new_value

In Ruby, you use square brackets [] to get or set values in arrays and hashes.

For variables, just use the variable name to access or assign a value.

Examples
This gets the value at index 1 (second item) from the array.
Ruby
arr = [10, 20, 30]
puts arr[1]  # Accessing the second element
This changes the third item in the array to 50.
Ruby
arr = [10, 20, 30]
arr[2] = 50  # Setting the third element
puts arr.inspect
This gets the value for the key "name" from the hash.
Ruby
h = {"name" => "Alice", "age" => 25}
puts h["name"]  # Accessing value by key
This updates the "age" key to 26 in the hash.
Ruby
h = {"name" => "Alice", "age" => 25}
h["age"] = 26  # Setting a new value for key
puts h.inspect
Sample Program

This program shows how to get and change values in an array and a hash.

Ruby
arr = [5, 10, 15]
puts "Original array: #{arr.inspect}"

# Access the first element
first = arr[0]
puts "First element: #{first}"

# Change the second element
arr[1] = 20
puts "Updated array: #{arr.inspect}"

# Using a hash
person = {"name" => "Bob", "city" => "NY"}
puts "Original hash: #{person}"

# Access name
puts "Name: #{person["name"]}"

# Set new city
person["city"] = "LA"
puts "Updated hash: #{person}"
OutputSuccess
Important Notes

Remember, array indexes start at 0 in Ruby.

When setting a value, if the key or index does not exist, Ruby will add it (for hashes) or expand the array.

Summary

Use square brackets [] to access or set values in arrays and hashes.

Accessing means reading a value; setting means changing or adding a value.

Indexes in arrays start at zero, keys in hashes can be strings or symbols.