Skip to content

Commit f608b48

Browse files
authored
Merge pull request #26 from csalmeida/variable-scope
Variable Scope
2 parents 5d78eea + 90d72ad commit f608b48

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ Introduction to core features of the [Ruby](https://www.ruby-lang.org) programmi
4444
- [Merge Methods](#merge-methods)
4545
- [Custom Methods](#custom-methods)
4646
- [Define and Call Methods](#define-and-call-methods)
47+
- [Variable Scope](#variable-scope)
4748
</details>
4849

4950
# Getting Started
@@ -1504,4 +1505,29 @@ end
15041505
greet('Skoglund')
15051506
```
15061507

1507-
A method doesn't need to have arguments, but if it does, different data can be passed in each time it's called.
1508+
A method doesn't need to have arguments, but if it does, different data can be passed in each time it's called.
1509+
1510+
## Variable Scope
1511+
1512+
This section expands on the concept of variable scope, as in where variables can be accessed from in a script depending on how they get defined.
1513+
1514+
When a variable is defined without any [scope indicators](#variables), it defaults to a local variable. A variable defined inside a method is also considered a local variable, however, it cannot be accessed outside the method, the same way a local variable defined outside a method cannot be used inside one.
1515+
1516+
> Local variables inside methods only have scope inside methods.
1517+
1518+
Global, class and instance variables will have scope both outside and inside methods. This will be expanded later.
1519+
1520+
```ruby
1521+
# custom-methods/variable-scope.rb
1522+
value = 10
1523+
1524+
def output_value
1525+
value = 5
1526+
puts value
1527+
end
1528+
1529+
output_value # Will print 5, not 10.
1530+
puts value # Will print 10, not 5.
1531+
```
1532+
1533+
The example above shows how two variables called `value` were defined and are different as they belong to different local scopes. `value = 10` is scoped to the wider structure of the document whilst `value = 5` is scoped to the `output_value` method.

custom-methods/variable-scope.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!usr/bin/env ruby
2+
3+
# A local variable called value defined on the file itself.
4+
value = 10
5+
6+
# A method with its own local variable called value.
7+
def output_value
8+
value = 5
9+
puts value
10+
end
11+
12+
# Both variables were defined in their local scopes, therefore they print different values.
13+
output_value # Will print 5, not 10.
14+
puts value # Will print 10, not 5.

0 commit comments

Comments
 (0)