Information Technology Reference
In-Depth Information
STRINGS, SYMBOLS, AND MASHES
So far, we have been using the symbol syntax for hashes. The syntax is:
key : value
This is Ruby syntactic sugar for the following:
:key => value
The => is called a hash rocket .
Symbols are immutable strings in Ruby. Other languages would call them constants. We are
using symbols in the preceding example, but the next code snippet demonstrates using strings
as hash keys:
hash = { 'key' => value }
hash [ 'key' ] #=> value
No tice that the way in which the key is accessed also changes.
In Chef, you'll most commonly see string keys for consistency. However, Chef actually uses a
custom data structure known as a mash . Mashes do not care about the data type you use to ac-
cess a given element in a hash. In a mash, the following are all equivalent:
mash = Hashie : :Mash . new ({ key : value })
mash [ :key ] #=> value
mash [ 'key' ] #=> value
mash . key
#=> value
Ha shie::Mash is not part of the core Ruby library.
Mashes are great because they do not enforce a specific key construct. You can use the form
that makes the most sense to you.
For example, you can use Ruby hashes to store information about popular baseball
players and their current statistics. The key in this hash was the name of the baseball
 
 
 
 
Search WWH ::




Custom Search