Tuesday, November 5, 2019

How to Create and Use Hashes in Ruby

How to Create and Use Hashes in Ruby Arrays are not the only way to manage collections of variables in Ruby. Another type of collection of variables is the hash, also called an associative array. A hash is like an array in that its a variable that stores other variables. However, a hash is unlike an array in that the stored variables are not stored in any particular order, and they are retrieved with a key instead of by their position in the collection. Create a Hash With Key/Value Pairs A hash is useful to store what are called key/value pairs. A key/value pair has an identifier to signify which variable of the hash you want to access and a variable to store in that position in the hash. For example, a teacher might store a students grades in a hash. Bobs grade would be accessed in a hash by the key Bob and the variable stored at that location would be Bobs grade. A hash variable can be created the same way as an array variable. The simplest method is to create an empty hash object and fill it with key/value pairs. Note that the index operator is used, but the students name is used instead of a number.​​ Remember that hashes are unordered, meaning there is no defined beginning or end as there is in an array. So, you cannot append to a hash. Values are simply inserted into the hash using the index operator. #!/usr/bin/env rubygrades Hash.newgrades[Bob] 82grades[Jim] 94grades[Billy] 58puts grades[Jim] Hash Literals Just like arrays, hashes can be created with hash literals. Hash literals use the curly braces instead of square brackets and the key value pairs are joined by . For example, a hash with a single key/value pair of Bob/84 would look like this: { Bob 84 }. Additional key/value pairs can be added to the hash literal by separating them with commas. In the following example, a hash is created with the grades for a number of students. #!/usr/bin/env rubygrades { Bob 82,Jim 94,Billy 58}puts grades[Jim] Accessing Variables in the Hash There may be times when you must access each variable in the hash. You can still loop over the variables in the hash using the each loop, though it wont work the same way as using the each loop with array variables. Because a hash is unordered, the order in which each will loop over the key/value pairs may not be the same as the order in which you inserted them. In this example, a hash of grades will be looped over and printed. #!/usr/bin/env rubygrades { Bob 82,Jim 94,Billy 58}grades.each do|name,grade|puts #{name}: #{grade}end

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.