Skip to content

Instantly share code, notes, and snippets.

@theHamdiz
Created February 18, 2016 23:53
Show Gist options
  • Select an option

  • Save theHamdiz/9191a56def213a187689 to your computer and use it in GitHub Desktop.

Select an option

Save theHamdiz/9191a56def213a187689 to your computer and use it in GitHub Desktop.
This gist describes how you can treat a single item like an array in ruby by just prefixing it with the asterisk operator(*)
class Fixnum
def digits_count
# a cool trick to return the base 10 logarithm of x.
# which always defaults to the actual number of digits - 1
Math.log10(self).to_i + 1 # here we add the missing 1.
end
end
# a single random number
item = rand(9999999)
# just a dummy array
items = [1,2,3,4,5]
# prefixing the single Fixnum object with asterisk treats it..
# like an array of one element which of course is 'item'
[*item].each { |i| puts i }
# just to print a nice separator that fits with the random number digit count.
puts "-" * item.digits_count
[*items].each { |i| puts i }
# the same as
Array(item).each{ |i| i }
Array(items).each{ |i| i }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment