Close

Ruby – Methods

In ruby, methods works the same way as c# methods do.

Announcement

I have released my new course on Udemy, Kubernetes By Example. Sign up now to get free lifetime access!

you can have static and instance methods.

you define methods using the “def” keyword and construct:

def MethodName (OptionalParameters)
   puts OptionalParameter 
end

for example if we have:

$ cat testscript.rb
#!/usr/bin/env ruby

def WelcomeMessage (a_message)
  puts a_message
end

a_string = "Hello World!"
WelcomeMessage a_string

Then we will end up with:

$ ./testscript.rb
Hello World!

Here, the “puts” command is the ruby equivalent of bash’s “echo” command, or powershell’s “write-host” command.

There are a number of other ruby commands that you can use straight from the command line. These commands are available because the kernel module is always automatically loaded.

For example here I have created an .rb file called helloworld2.rb with the following 3 methods:

[ruby]
def simple_welcome
puts "Hello"
end

puts "the simple_welcome method outputs:"
simple_welcome # notice how we call this method like a normal command.

def normal_welcome (name)

# If you want to insert a variable inside double-quotes, then you need to
# encase it in #{…} syntax
puts "Hello #{name}"
end

puts "the normal_welcome method outputs"

normal_welcome ("CodingBee")

def complex_welcome (name1, name2, name3)
puts "Hello #{name1}, #{name2}, and #{name3}"
end

puts "The complex_welcome method outputs"
complex_welcome("Tom", "Jerry", "CodingBee") # Note for some reason you have any whitespace before opening bracket.
[/ruby]

The above code outputs:

C:\RailsInstaller\Ruby1.9.3\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) C:/Users/Mir/RailsProjects/spec2xmlproj/helloworld2.rb
the simple_welcome method outputs
Hello
the normal_welcome method outputs
Hello CodingBee
The complex_welcome method outputs
Hello Tom, Jerry, and CodingBee

Any variables set in a method will be confined to that method’s scope. Also a method can’t access any variables outside it’s scope. e.g.:

website_name = "codingbee"
puts website_name

def normal_welcome
  # puts website_name           # this will output an error message, hence commented out.  
  website_name = "google"
  puts website_name
end

normal_welcome

puts website_name

This outputs:

PS C:\Temp\irb> ruby .\scope.rb
codingbee
google
codingbee
PS C:\Temp\irb>

If you want a variable accessible/settable everywhere, then you need to create a “global variable”. global variables are prefixed with the dollar symbol, e.g.:

[ruby]
$website_name = ‘codingbee’
puts $website_name

def normal_welcome

puts $website_name
$website_name = ‘google’
end

normal_welcome

puts $website_name
[/ruby]

The above outputs:

$ ./testscript.rb
codingbee
codingbee
google

Note: if you a method to output an object instead of using “puts” output, then simply specify the object as the last line in the method.