Skip to content

Instantly share code, notes, and snippets.

@mipearson
Created December 25, 2011 07:04
Show Gist options
  • Save mipearson/1518836 to your computer and use it in GitHub Desktop.
Save mipearson/1518836 to your computer and use it in GitHub Desktop.
# Is there a better way to perform the below?
var = begin
if herp
'derp'
elsif qux
'baz'
else
'foo'
end
end
# I dislike the following variant as it is a small DRY violation
# and can have unexpected scoping issues if you forget to preset
# var to nil.
var = nil
if herp
var = 'derp'
elsif qux
var = 'baz'
else
var = 'foo'
end
# There's also:
var = 'foo'
var = 'derp' if herp
var = 'baz' if qux
# but I find it non-obvious.
@deepfryed
Copy link

scoping rules have changed in 1.9

#!/usr/bin/env ruby

case rand(10)
  when 0 then somevar = 1 
  when 1 then somevar = 2 
end

p 'what scoping issues, champ ?', somevar

@fuelxc
Copy link

fuelxc commented Dec 25, 2011

No need for the begin

var = if herp
'derp'
elsif qux
'baz'
else
'foo'
end

@mipearson
Copy link
Author

@fuelxc: Ah! I didn't know that. Cheers.

@deepfryed: Most of my for $$ work is REE 1.8.7. Most other things are gems and so I want to keep them working under MRI 1.8.7. Good to know they've changed that, though.

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