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

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 conclusion is as follows:

we enter something funny
yes
no
return else -> no 

Why can't I get an error? What does def/ else/ mean end?

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

+4
source share
1 answer

This is actually part of a larger syntax 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! Therefore, you can leave rescueand ensureto get your example.

+12
source

Source: https://habr.com/ru/post/1545884/


All Articles