Concept Flow - Accessing and setting values
Start
Access value by key/index
Use value or modify it
Set new value by key/index
Check updated value
End
This flow shows how to get a value from a data structure and then change it by setting a new value.
hash = {a: 1, b: 2}
puts hash[:a]
hash[:a] = 10
puts hash[:a]| Step | Action | Expression | Result | Output |
|---|---|---|---|---|
| 1 | Create hash | hash = {a: 1, b: 2} | {:a=>1, :b=>2} | |
| 2 | Access value by key :a | hash[:a] | 1 | 1 |
| 3 | Set new value for key :a | hash[:a] = 10 | 10 | |
| 4 | Access updated value by key :a | hash[:a] | 10 | 10 |
| Variable | Start | After Step 1 | After Step 3 | Final |
|---|---|---|---|---|
| hash | nil | {:a=>1, :b=>2} | {:a=>10, :b=>2} | {:a=>10, :b=>2} |
Accessing and setting values in Ruby: - Use hash[key] to get a value. - Use hash[key] = value to set or update. - Access returns current value. - Setting changes the stored value. - Works similarly for arrays with indexes.
arr in Ruby using indexing?arr[0].arr[0] correctly accesses the first element. arr[1] accesses the second element. arr.first() is a method call that also returns the first element but is not using square brackets. arr.get(0) is invalid syntax in Ruby.:name to "Alice" in a Ruby hash person?=.person[:name] = "Alice" correctly sets the key :name. person.name = "Alice" is invalid for hashes. person["name"] = Alice misses quotes around Alice, causing error. person[:name] == "Alice" is a comparison, not assignment.arr = [10, 20, 30] arr[1] = 50 puts arr.inspect
arr[1] = 50 changes the element at index 1 (second element) to 50.person = {name: "Bob"}
person.name = "Charlie"person.name = "Charlie" tries to use dot notation, which is invalid for hashes and causes an error.data = {user: {name: "Eve", age: 28}}, how do you change the user's age to 30?data[:user][:age].data[:user][:age] = 30 to update the age.Pass the test and this pattern moves unknown