Difference between or and || operator.
Both or and || return their first argument unless it isfalse, in which case they evaluate and return their second argument. This is shown in the following example:
- puts nil || 2008
- puts false || 2008
- puts "ruby" || 2008
The output is:
- >ruby test.rb
- 2008
- 2008
- ruby
- >Exit code: 0
var1 = 5;
var2 = '2'
puts var1 + var2.to_i
Global scope and global variables
We're starting with the scope that's used least often, but which you need to be aware of: global scope, meaning scope that covers the entire program. Global scope is enjoyed by global variables. Global variables are distinguished by starting with a dollar-sign ($) character. They are available everywhere in your program. Global variables never go out of scope. However, global variables are used very little by experienced programmers (except perhaps a few of the built-in ones).
Built-in global variables
The Ruby interpreter starts up with a fairly large number of global variables already initialized. These variables store information that's of potential use anywhere and everywhere in your program. For example, the global variable$0 contains the name of the file Ruby is executing. The global $: (dollar sign followed by a colon) contains the directories that make up the path Ruby searches when you load an external file.$$ contains the process id of the Ruby process. And there are more.
Local scope
- The top level (outside of all definition blocks) has its own local scope.
- Every class or module definition block (class, module) has its own local scope,even nested class/module definition blocks.
- Every method definition (def) has its own local scope.