summaryrefslogtreecommitdiffhomepage
path: root/samples/00_learn_ruby_optional/00_intermediate_ruby_primer/app/07_functions.txt
blob: 9ad38de4075478a72479ecda0762a945bf424bd9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# ====================================================================================
# Functions
# ====================================================================================

# The last statement of a function is implictly returned. Parenthesis for functions
# are optional as long as the statement can be envaluated disambiguously.

repl do
  puts "* RUBY PRIMER: Functions"
end

# ====================================================================================
# Functions single parameter
# ====================================================================================

repl do
  puts "* INFO: Function with one parameter"

  # function definition
  def add_one_to n
    n + 1
  end

  # Parenthesis are optional in Ruby as long as the
  # parsing is disambiguous. Here are a couple of variations.
  # Generally speaking, don't put parenthesis is you don't have to.

  # Conventional Usage of Parenthesis.
  puts add_one_to(3)

  # DragonRuby's recommended use of parenthesis (inner function has parenthesis).
  puts (add_one_to 3)

  # Full parens.
  puts(add_one_to(3))

  # Outer function has parenthesis
  puts(add_one_to 3)
end

# ====================================================================================
# Functions with default parameter values
# ====================================================================================

repl do
  puts "* INFO: Function with default value"
  def function_with_default_value v = 10
    v * 10
  end

  puts "Passing the argument three yields: #{function_with_default_value 3}"
  puts "Passing no argument yields: #{function_with_default_value}"
end

# ====================================================================================
# Nil default parameter value and ||= operator.
# ====================================================================================

repl do
  puts "* INFO: Using the OR EQUAL operator (||=)"
  def function_with_nil_default_with_local a = nil
    result   = a
    result ||= "DEFAULT_VALUE_OF_A_IS_NIL_OR_FALSE"
    "value is #{result}."
  end

  puts "Passing 'hi' as the argument yields: #{function_with_nil_default_with_local 'hi'}"
  puts "Passing nil: #{function_with_nil_default_with_local}"
end