Skip to content

Instantly share code, notes, and snippets.

@joho
Forked from lightningdb/gist:47739
Created January 16, 2009 00:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joho/47746 to your computer and use it in GitHub Desktop.
Save joho/47746 to your computer and use it in GitHub Desktop.
# what is the idiomatic ruby for this:
# if the var is an array, do_something with each element, otherwise just do something with the var
# if var.is_a?(Array)
# var.each do |element|
# do_something(element)
# end
# else
# do_something(var)
# end
class Object
def for_this_or_each(&block)
# make work for any enumerable, not just arrays
if respond_to? :each
each &block
else
block.call self
end
end
end
var.for_this_or_each { |o| do_something(o) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment