Lowongan Kerja

Galleri Foto Artis

Gallery Tattos

14.2. Variables
Ruby supports a couple different types of variables, instance variables and class variables. Instead of making you guess whether their names actually mean what they say, I'll just come out and say it. The names mean what they say. Instance variables are created for each instance of the class. With class variables, on the other hand, all instances of the class share one variable. Although instance variables are common, class variables are somewhat less so. This does not mean that they aren't as useful; in fact, many times there is simply no substitute for a class variable.

The only question concerning variables is how to distinguish between instance variables and class variables. Are there little signs hanging off them that say "instance variable" and "class variable"? In a word, yes.

Instance variables and class variables are distinguished by the prefix. Instance variables are prefixed by a single @, whereas class variables are prefixed by two @. So @Bob is an instance variable, and @@Paul is a class variable.

Now that we have someplace to put our information, let's do something to it.

14.3. Operators
Regardless of the language, there is usually some commonality. There's addition, subtraction, multiplication, division, and assignment. In some languages, including Ruby and JavaScript, the addition operator does double duty as the concatenation operator. This means that examples such as the following are pretty much the same, regardless of the language:

X = 1 + 1
X = 1 1
X = 1 * 1
X = 1 / 1



However, occasionally will you see something a little out of the ordinary, usually in languages that borrow some of their syntax from C. In Ruby, they're called multiple assignments; I like to think of them as less typing. Consider, for a moment, the following line of code:

X = X + 5


All that it does is increment the variable X by 5, so wouldn't it be easier to type this instead?

X += 5


Yeah, all that I'm saving is two keystrokes, the second X and a space, but it adds up. Imagine for a moment the variable name was my last name, Woychowsky instead of X. Having to type it only once would greatly extend the life of the W key. The same shortcut is available for subtraction, multiplication, and division.


Related Posts



0 comments:

Post a Comment

 

Networking

FOREX TRADER

Sexi Women

Copyright © Free ebooks Download | Powered by Blogger | Template by Blog Go Blog