Methods
Every thing in Ruby is object, object created from a Class, and it has many methods.
Table of contents
- Method call
- Three kinds of method
- Define method
- Write a method by code block
- Use Variable Arguments to Capture as Many Values as Necessary
Method call
object . method (params 1, params 2, …, params n) Ruby use .
between object and method, use ()
put params.
irb(main):001:0> 'KodaCamp'.size
=> 8
# 'KodaCamp': it's an object created from String
# . : call method
# method: size
# => 8 is return value
call method with block, for example each
object.method(params, …) do |value 1, value 2, …| code block end
irb(main):001:0> 3.times do |i|
irb(main):002:1* puts "the #{i} times loop"
irb(main):003:1> end
the 0 times loop
the 1 times loop
the 2 times loop
=> 3
so… what’s 1 + 1 in Ruby
irb(main):001:0> 1 + 1
=> 2
the first 1
is an object created by Integer.
+
is the method
the second 1
is params
# it's the real process
irb(main):001:0> 1.+(1)
=> 2
Three kinds of method
instance method
Every object in Ruby is instance, it’s created by a Class. Ruby will define instance methods in every class.
irb(main):001:0> 10.to_s
=> "10"
irb(main):002:0> [1, 2, 3].size
=> 3
Ruby can call methods
, and Ruby will show all instance methods.
irb(main):001:0> 10.methods
=> [:-@, :**, :<=>, :upto, :<<, :<=, :>=, ...... :define_singleton_method, :public_method, :extend, :to_enum, :enum_for, :=~, :!~, :respond_to?, :freeze, :object_id, :send, :display, :nil?, :hash, :class, :singleton_class, :itself, :yield_self, :then, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :equal?, :!, :__id__, :instance_exec, :!=, :instance_eval, :__send__]
class method
The Method from the Class, like Array
, Hash
, Time
etc……
irb(main):001:0> Array.new
=> []
irb(main):002:0> Time.now
=> 2022-12-01 00:00:00 +0000
functional method
It’s not from any reciver(object or Class). ex: puts
, sleep
irb(main):001:0> puts 'Kodacamp'
Kodacamp
=> nil
irb(main):002:0> sleep(3)
=> 3
Define method
method name can compose of English letters, numbers, and underscores, but cannot start with a number.
def method_name( param 1, param 2, …)
# code block
end
We still not introduce how to create a Class
or object, so we only talk about how to define a method.
# hello_with_name.rb
def hello(name)
puts "Hello, #{name}."
end
hello("Ruby")
run Ruby code
$~ ruby hello_with_name.rb
Hello, Ruby.
Ruby can give a default value to the params if run hello
, without any params, it will show an error.
hello_with_name.rb:1:in `hello': wrong number of arguments (given 0, expected 1) (ArgumentError)
Edit the function
# hello_with_name.rb
def hello(name = 'Default Value')
puts "Hello, #{name}."
end
hello("Ruby")
hello
Run Ruby code again
$~ ruby hello_with_name.rb
Hello, Ruby.
Hello, Default Value.
default value only from right to left.
# Correct
def function(a, b = 1, c = 2)
end
# Wrong
def function(a = 1, b, c = 2)
end
def function(a = 2, b = 1, c)
end
return value:
Ruby will return the least line result to the return value
# return_value.rb
def volume(x, y, z)
x * y * z
end
puts volume(2, 3, 4)
# run
$~ ruby return_value.rb
24
return value and print in console are different
every method has return value
irb(main):001:0> 3.times {|i| puts "this #{i} times loop"} this 0 times loop this 1 times loop this 2 times loop => 3
all the content this i times loop only print on console,
3.times
the return value is3
irb(main):001:0> try_return = 3.times {|i| puts "this #{i} times loop"} ... irb(main):002:0> try_return => 3
Ruby can assign return value to variable.
Write a method by code block
# function_code_block.rb
def myloop
while true
yield
end
end
num = 1
myloop do
puts "num is #{num}" # print num in console
break if num > 100 # if num over 100 stop loop
num *= 2 # num = num *2
end
It’s the first time use yield
in this textbook
# it looks like Ruby will put
puts "num is #{num}"
break if num > 100
num *= 2
# into
yield
# and run the code block
$~ ruby block.rb
num is 1
num is 2
num is 4
num is 8
num is 16
num is 32
num is 64
num is 128
Use Variable Arguments to Capture as Many Values as Necessary
take an unlimited number of values
# print_all_params.rb
def print_all_params(*args)
args.each {|arg| puts arg}
end
print_all_params(1, 2, 3, 4, 5)
$~ ruby print_all_params.rb
1
2
3
4
5
Ruby can assign one params reqired
# print_all_params.rb
def print_all_params(first_params, *args)
puts "first params is #{first_params}"
args.each {|arg| puts "args: #{arg}"}
end
print_all_params(1, 2, 3, 4, 5)
$~ ruby print_all_params.rb
first params is 1
args: 2
args: 3
args: 4
args: 5
Ruby only can use one time *
in params, and *
arg is an Array
# print_all_params.rb
def print_all_params(first_params, *args, last_params)
puts "first params is #{first_params}"
puts "last params is #{last_params}"
puts "*args is #{args.class}"
args.each {|arg| puts "args: #{arg}"}
end
print_all_params(1, 2, 3, 4, 5)
$~ ruby print_all_params.rb
first params is 1
last params is 5
*args is Array
args: 2
args: 3
args: 4
Ruby also can use Hash to pass the params
def area2(x: 0, y: 0, z: 0)
xy = x * y
yz = y * z
zx = z * x
(xy + yz + zx ) * 2
end
args1 = {x: 2, y: 3, z: 4}
p area2(args1) #=> 52
args2 = {x: 2, z: 3} #=> skip y, it will use default value 0
p area2(args2) #=> 12
Ruby can skip { ~ }
to show it’s a hash
def foo(arg)
arg
end
p foo({"a"=>1, "b"=>2}) #=> {"a"=>1, "b"=>2}
p foo("a"=>1, "b"=>2) #=> {"a"=>1, "b"=>2}
p foo(a: 1, b:2) #=> {:a=>1, :b=>2}
By default, Ruby will let the last params can be a hash.
def bar(arg1, arg2)
[arg1, arg2]
end
p bar(100, {"a"=>1, "b"=>2}) #=> [100, {"a"=>1, "b"=>2}]
p bar(100, "a"=>1, "b"=>2) #=> [100, {"a"=>1, "b"=>2}]
p bar(100, a: 1, b: 2) #=> [100, {:a=>1, :b=>2}]