Firstly the syntax. Let’s first define a very basic function we can use for this post.
12345678
defprint_stuff(str1,str2,reverse=false)ifreverseputs"#{str2} and #{str1} received!"elseputs"#{str1} and #{str2} received!"endstr=str1+str2end
Calling functions
Brackets around function parameters is optional in Ruby. However, sometimes it’s useful to include them regardless for clarity’s sake.
12345
print_stuff("First argument","Second argument")# First argument and Second argument received!print_stuff"First argument","Second argument"# First argument and Second argument received!
Arguments can be made optional by giving them a default value.
12345
print_stuff("First argument","Second argument",false)# First argument and Second argument received!print_stuff("First argument","Second argument",true)# Second argument and First argument received!
Return value
As you may have already noticed, print_stuff does use return even though it does exist in Ruby and it does exactly what you’d expect. If the return value is not specified, Ruby will return the value returned in the last executed line of the block
Because print "add successful" returns nil, add_print returns nil.
Error Handling
1234567891011121314
defdo_somethingraise"Failed to do something"enddo_something# RuntimeError: Failed to do somethingbegindo_somethingputs"Done something"rescueputs"Rescuing from exception"end# Rescuing from exception
retry will return the cursor to start of the begin block it belongs to
1234567891011121314
i=0beginputs"#{i}"i+=1ifi<2do_somethingendputs"All done!"rescueretryend# 0# 1# All done!