Skip to content

Instantly share code, notes, and snippets.

@hosh
Forked from joelg/hello_loop.rb
Created May 25, 2010 01:27
Show Gist options
  • Save hosh/412648 to your computer and use it in GitHub Desktop.
Save hosh/412648 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
def hello_loop(names)
names.each do |name|
puts "Hello #{name}"
end
end
hello_loop(%w(
Gafitescu
D_Roch
Steven_Ng
n0x13
hosheng
Pratik_Desal
r_kumar
Ashley_Moran
persiancoffee
Andre_Fischer))
# Notice how %w will delimit on space, so names will have to have _.
# Some other tricks
puts %w(
Gafitescu
D_Roch
Steven_Ng
n0x13
hosheng
Pratik_Desal
r_kumar
Ashley_Moran
persiancoffee
Andre_Fischer).map { |name| "Hello #{name}" }
# Splat operator some of the commentators were talking about
def say_hello!(*names)
puts names.map {|name| "Hello #{name}" }
end
say_hello!("Gafitescu", "D_Roch", "Steven_Ng","n0x13")
# Someone in the comments mentioned adding a #to_hello, but the example
# was incomplete. You have to reopen the Array class (yes, after it has been
# defined) and add the to_hello method.
class Array
def to_hello
self.map { |i| "Hello #{name}" }
end
end
puts %w(
Gafitescu
D_Roch
Steven_Ng
n0x13
hosheng
Pratik_Desal
r_kumar
Ashley_Moran
persiancoffee
Andre_Fischer).to_hello
# To keep things more organized, projects such as Rails or Merb will
# have core extensions separated out into namespaced modules and then
# including them into the the array.
module MyNamespace
module CoreExt
module Array
def say(something = "Hello")
self.map { |i| "#{something} #{name}" }
end
end
end
end
class Array
include MyNamespace::CoreExt::Array
end
# Or a shorter way:
Array.send(:include, MyNamespace::CoreExt::Array)
puts %w(
Gafitescu
D_Roch
Steven_Ng
n0x13
hosheng
Pratik_Desal
r_kumar
Ashley_Moran
persiancoffee
Andre_Fischer).say("Ni Hao,")
# I highly recommend playing with irb since you can do things like
# [].methods.sort to inspect what you can call. Same with
# {}.methods.sort
# You don't always need to drop this into a file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment