You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on May 23, 2020. It is now read-only.
In Hashes, if you are trying to access a key which do not exist, Ruby return __nil__. It is Ruby's way of saying nothing at all. __=>__ is called the **hash rocket** symbol.
299
+
300
+
Hashes can also be defined using _symbols_:
301
+
```ruby
302
+
menagerie = { :foxes => 2,
303
+
:giraffe => 1,
304
+
:weezards => 17,
305
+
:elves => 1,
306
+
:canaries => 4,
307
+
:ham => 1
308
+
}
309
+
```
310
+
**_Note_**: Hash lookup is faster with symbol keys than with string keys.
311
+
312
+
Symbols are not strings. There can be different strings all having the same value, there's only one copy of any particular symbol at a given time. Symbols always start with a colon (:). They must be valid Ruby variable names. These are mainly used as hash keys or for referencing method names.
313
+
```ruby
314
+
"string == :string #false
315
+
```
316
+
317
+
The **.object_id** method gets the ID of an object. It's how Ruby knows whether two objects are the exact same object.
318
+
```ruby
319
+
puts "string".object_id
320
+
puts :symbol.object_id
321
+
```
322
+
323
+
_.to_s_ and _.to_sym_ can be used for interconversion between strings and symbols.
324
+
```ruby
325
+
:hellothere.to_s
326
+
# ==> "hellothere"
327
+
328
+
"hellothere".to_sym
329
+
# ==> :hellothere
330
+
```
331
+
__.inter__ works the same as _.to_sym_.
332
+
333
+
In Ruby 1.9, the hash definition syntax changed.
334
+
```ruby
335
+
new_hash = {
336
+
one: 1,
337
+
two: 2,
338
+
three: 3
339
+
}
340
+
```
341
+
The keys are still symbols.
342
+
343
+
__.select__ method can be used on hashes for filtering out data based on some condition.
344
+
```ruby
345
+
grades = { rita: 100,
346
+
mita: 97,
347
+
ayush: 56,
348
+
jane: 83
349
+
}
350
+
351
+
grades.select { |name, grade| grade <= 97 }
352
+
# ==> { :rita => 100, :mita => 97 }
353
+
```
354
+
355
+
Every time in .each block for hashes we have to define variables for key as well value. Ruby has two methods __.each_key__ and __.each_value__ to overcome this problem.
0 commit comments