简体   繁体   中英

What is the difference between symbols?

I checked that :xyz == 'xyz' is false . But we can call functions inside rails with :index or 'index' . Please clear my wonder.

:xyz and 'xyz' are indeed different. That does not contradict with the fact that a method can take either type of argument. For example, Array#* can take a String or Integer as an argument:

["a", "b"] * "foo" # => "afoob"
["a", "b"] * 2 # => ["a", "b", "a", "b"]

but that does not mean that "foo" is the same as 2 .

And if you follow the logic you are implying, it would mean that all objects in Ruby are the same.

I checked that :xyz == 'xyz' is false . But we can call functions inside rails with :index or 'index' . Please clear my wonder.

There is nothing mysterious about this.

Symbol#== is a method just like any other method. The person who wrote it, wrote it in such a way that it returns false . She could have written it to return true or return 42 or format your harddisk, but she decided to return false .

Rails methods are methods just like any other method. The person who wrote them, wrote them in such a way that accepts either Symbol s or String s. She could have written them to accept only Symbol s or only String s or to accept only String s on even days of the week, only String s on odd days of the week, and only Integer s during a full moon, but she decided to accept both String s and Symbol s.

The developers who write Rails and the developers who write Ruby are free to do in their methods whatever they want, just like you are free to do whatever you want in methods you write. You can write a method that accepts String s, you can write a method that accepts Symbol s, you can write a method that accepts both, you can write a method that accepts neither. It's your choice, just like it is the choice of the Rails and Ruby developers.

It implies absolutely nothing about the relationship between Symbol s and String s.

My guess is that you've come across Rails' use of HashWithIndifferentAccess . This allows you to access a Hash using either a Symbol or a String.

In other words, params[:a] is the same as params["a"] because internally, HashWithIndifferentAccess converts all the keys to strings.

See the documentation for more information.

:xyz is a symbol. A symbol is an instance of the class Symbol .

"xyz " is a string. A string is not a Symbol.

Therefore, :xyz=='xyz' is not true. Because the instance of Symbol that is :xyz is not equivalent to the instance of String xyz .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM