Skip to content

Instantly share code, notes, and snippets.

@laginha87
Created May 2, 2018 18:15
Show Gist options
  • Save laginha87/0fce74643c95bbd15294f8414ef5f7e5 to your computer and use it in GitHub Desktop.
Save laginha87/0fce74643c95bbd15294f8414ef5f7e5 to your computer and use it in GitHub Desktop.
not_nil_branching_failure
a = [1,2,3, nil]
if a[0]
puts a[0] + 1 # This doesn't work
end
puts a[0].not_nil! + 1 # This does though
@marksiemers
Copy link

The workaround for this is to use a temporary variable in the if statement:

a = [1,2,3, nil]

if temp = a[0]
  puts temp + 1 # This doesn't work
end

puts a[0].not_nil! + 1 # This does though

Not quite as easy as ruby, but once you get used to this, it starts to feel natural.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment