Ruby - Objects and Variables
Objects
Everything is Ruby is an object, the Object class is the parent class of all classes in Ruby. Its methods are therefore available to all objects unless explicitly overridden.
An important method in the Object class is class(). It returns the “type” of an object.
> 1.class() # => Fixnum > 1.class # => Fixnum > 1.0.class # => Float > "Foo".class # => String
Notice how parentheses are optional – they are commonly omitted.
The language syntax is sensitive to the capitalization of identifiers, in most cases treating capitalized variables as constants.
Variables
Ruby does not use variable declarations, if you assign a value to a literal, an “appropriate” variable named after that literal is created.
Example
> a = 2 # => 2 > a # => 2In this example, a has type Fixnum, this is an integer data in Ruby. The other integer type is Bignum (represents numbers of arbitrary size).
Example
> a = "2" # => "2" > a # => "2"Now a is a String variable.
Important: All assignments are done by reference in Ruby. I.e, a variable just holds a reference to an object, and does not care about the type of the object.
Ruby supports parallel assignment.
Example: You can easily swap the values stored in two variables:
> a = 2 # => 2 > b = 1 # => 1 > puts a, b # 2 # 1 # => nil a, b = b, a # => [1, 2]
Ruby uses simple naming conventions to denote the scope of variables:
- name – could be a local variable.
- @name – an instance variable.
- @@name – a class variable.
- $name – a global variable.
Furthermore, local variables must begin with a lowercase letter, and the convention is to use underscores, rather than camel case, for multi-word names.
Constants are any name that starts with an uppercase letter, and the convention is to use underscores.
Classes and modules are treated as constants, so they begin with uppercase letters, and the convention is to use camel case.
Latest Post
- Dependency injection
- Directives and Pipes
- Data binding
- HTTP Get vs. Post
- Node.js is everywhere
- MongoDB root user
- Combine JavaScript and CSS
- Inline Small JavaScript and CSS
- Minify JavaScript and CSS
- Defer Parsing of JavaScript
- Prefer Async Script Loading
- Components, Bootstrap and DOM
- What is HEAD in git?
- Show the changes in Git.
- What is AngularJS 2?
- Confidence Interval for a Population Mean
- Accuracy vs. Precision
- Sampling Distribution
- Working with the Normal Distribution
- Standardized score - Z score
- Percentile
- Evaluating the Normal Distribution
- What is Nodejs? Advantages and disadvantage?
- How do I debug Nodejs applications?
- Sync directory search using fs.readdirSync