Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a def ... else ... end construct?

Tags:

ruby

I have this code:

def with_else
  puts 'we enter something funny'
  if true
    puts "yes"
    'return YES'
  end
  'return what?'
else
  puts 'no'
  'return else -> no'
end

puts with_else

and the output is this:

we enter something funny
yes
no
return else -> no 

Why don't I get an error for that? What does def/else/end mean?

http://rubyfiddle.com/riddles/8df07

like image 804
halfbit Avatar asked Dec 14 '22 21:12

halfbit


1 Answers

This is actually part of a larger syntactical structure:

def foo
  # method stuff
rescue
  # stuff if an exception is caught
else
  # stuff if no exception is caught
ensure
  # always run after rescue and else
end

But each section is optional! So you can leave out the rescue and ensure to get your example.

like image 71
Max Avatar answered Jan 08 '23 05:01

Max