New to Rails and trying to get my head around when/why to use :symbols
, @ivars
, "strings"
within the framework.
I think I understand the differences between them conceptually
:symbol
instance per project@ivar
per instance"strings"
- as they are created whenever referenced (?) Feel free to correct me!
The main confusion comes from understanding the rules & conventions of what Rails expects - where and WHY?
I'm sure there's an "Ah ha!" moment coming but I haven't had it yet...as it seems pretty arbitrary to me (coming from C/Obj-C).
-thx
The :symbol , is as you mentioned it's an efficient way of representing names and strings; they are literal values. It is initialized and exists only once during the ruby session. It's not a string, since you don't have access to String methods; it's a Symbol. On top of that, it's immutable.
What is the difference between a symbol and a string? A string, in Ruby, is a mutable series of characters or bytes. Symbols, on the other hand, are immutable values. Just like the integer 2 is a value.
Ruby symbols are defined as “scalar value objects used as identifiers, mapping immutable strings to fixed internal values.” Essentially what this means is that symbols are immutable strings. In programming, an immutable object is something that cannot be changed.
%w(abc def xyz) is a shortcut for ["abc", "def","xyz"]. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them.
The @instance_variable
is an instance variable. It is usually defined in the controller and accessible in the views.
The "string"
is a string, like as in any other language.
The :symbol
, is as you mentioned it's an efficient way of representing names and strings; they are literal values. It is initialized and exists only once during the ruby session. It's not a string, since you don't have access to String methods; it's a Symbol. On top of that, it's immutable. For those reasons, it becomes very handy in representing keys in hashs. Rails methods uses hashes, thus, you find symbols a bit everywhere in Rails.
Instance variables are pretty straightforward: they track properties/values of a particular instance, so you use them when you the values will vary across instances.
Symbols vs. strings are a bit more arbitrary. Symbols are generally used for constant values, in much the same way that a language such as C would use enums; Ruby doesn't have enums, so symbols are often used to fill that gap. Strings are used for more varied pieces of text that won't be used as a flag or similar constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With