-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash.rb
More file actions
51 lines (40 loc) · 2.37 KB
/
Copy pathhash.rb
File metadata and controls
51 lines (40 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Hash
# A hash in Ruby is a collection of key-value pairs.
# Each key is unique and maps to a value. You can create a hash by enclosing key-value pairs in curly braces (`{}`) or by using the `Hash.new` constructor.
person = {
name: "Luthfi",
age: 25,
is_married: false,
live: {
city: "Jakarta",
country: "Indonesia"
}
}
puts person.inspect # Output: {:name=>"Luthfi", :age=>25, :is_married=>false, :live=>{:city=>"Jakarta", :country=>"Indonesia"}}
# Accessing values
puts person[:name] # Output: Luthfi
puts person[:age] # Output: 25
puts person[:live][:city] # Output: Jakarta
# Modifying values
person[:age] = 26
puts person[:age] # Output: 26
# Adding key-value pairs
person[:hobby] = "coding"
puts person.inspect # Output: {:name=>"Luthfi", :age=>26, :is_married=>false, :live=>{:city=>"Jakarta", :country=>"Indonesia"}, :hobby=>"coding"}
# Removing key-value pairs
person.delete(:is_married)
puts person.inspect # Output: {:name=>"Luthfi", :age=>26, :live=>{:city=>"Jakarta", :country=>"Indonesia"}, :hobby=>"coding"}
# Hash methods
puts person.keys.inspect # Output: [:name, :age, :live, :hobby] (Returns an array of all keys in the hash)
puts person.values.inspect # Output: ["Luthfi", 26, {:city=>"Jakarta", :country=>"Indonesia"}, "coding"] (Returns an array of all values in the hash)
puts person.has_key?(:name) # Output: true (Checks if the key :name exists in the hash)
puts person.has_value?("Luthfi") # Output: true (Checks if the value "Luthfi" exists in the hash)
# Hashes can also be nested, allowing you to create complex data structures. You can access nested values using multiple keys.
puts person.dig(:live, :country) # Output: Indonesia (Accessing the value of :country within the nested :live hash)
# delete method is used to remove a key-value pair from a hash by specifying the key. It returns the value associated with the removed key, or nil if the key was not found.
removed_value = person.delete(:hobby) # Removes the key :hobby and returns its value
puts removed_value # Output: coding (The value that was removed)
puts person.inspect # Output: {:name=>"Luthfi", :age=>26, :live=>{:city=>"Jakarta", :country=>"Indonesia"}} (The hash after the key-value pair has been removed)
# delete all hash elements
person.clear # This will remove all key-value pairs from the hash, leaving it empty.
puts person.inspect # Output: {} (The hash is now empty)