Skip to content

Instantly share code, notes, and snippets.

@lightningdb
Created January 16, 2009 00:45
Show Gist options
  • Save lightningdb/47739 to your computer and use it in GitHub Desktop.
Save lightningdb/47739 to your computer and use it in GitHub Desktop.
# brainfreeze!
# 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
# Thanks to Mike Gunderloy, this works a treat:
[*var].to_a.each { |element| do_something(element) }
# irb
*[[0,1,2,3],[4,5,6,7]].to_a.each { |ele| puts ele.class } # => Array Array
*[0,1,2,3].to_a.each { |ele| puts ele.class } # Fixnum Fixnum Fixnum Fixnum
[*0].to_a.each { |ele| puts ele.class } # Fixnum
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment