-2

I'm trying to learn rails and ruby. Then I face with a question

i found that we can create a function that only using symbol only. Instead of using the hashes.

for example:

a={b: "hash value", c: "another has value"}
printValue( :b)

is this one true?can you give example? I tried to search, but i cannot find it

wendy0402
  • 495
  • 2
  • 5
  • 16
  • possible duplicate of [How do functions use hash arguments in Ruby?](http://stackoverflow.com/questions/16576477/how-do-functions-use-hash-arguments-in-ruby) – Brad Werth Sep 05 '14 at 01:48
  • This is a pure-Ruby question, so no Rails tag, please. If you add an inappropriate tag, some members will waste time reading a question that will not interest them, while others who have filtered out questions with that tag may miss a question that would interest them. – Cary Swoveland Sep 05 '14 at 03:28
  • Thank you Cary, I've delete the rails tag – wendy0402 Sep 06 '14 at 06:55

1 Answers1

7

It's fairly common for people learning Ruby to not quite understand symbols. A symbol is a standard Ruby type, just like other built in Ruby types. Here is an example of how a symbol is just an object that is of a certain type:

'A'.class # => String
1.class # => Fixnum
:a.class # => Symbol

As with any other type, symbols have methods. If you open IRB and type :a.methods.sort it will show you all the methods you can call on a symbol. E.g., :a.to_s # => 'a'

As you've noticed, symbols are often used as Hash keys. However, other types can also be Hash keys:

my_hash = { 'A' => 'an A', 1 => 'a 1', :a => 'the symbol a'}
my_hash['A'] # => 'an A'
my_hash[1] # => 'a 1'
my_hash[:a] # => 'the symbol a'

Just like you can pass a String or other types to a method, you can pass a Symbol. In fact, in the last example, we are passing a String, a Fixnum, and then a Symbol to my_hash's [] method.

The reason people really like symbols for hash keys is that they are very lightweight to reuse. Here is an example showing one of the main differences between a symbol and any other object:

"a".object_id # => 70098399407740
"a".object_id # => 70098399393460
"a".object_id # => 70098399388140
:a.object_id # => 359368
:a.object_id # => 359368
:a.object_id # => 359368

As you can see, I create three strings that have the value "a", and they each have a different object id. In other words, there are three String objects in memory that contain the value "a". In contrast, every time I use :a it has the same object id. There is only one :a object in my entire program.

It's not uncommon to pass symbols to methods. You'll see this a lot in Rails.

Jay Mitchell
  • 1,230
  • 11
  • 14