Skip to content

Instantly share code, notes, and snippets.

@bsingr
Created August 19, 2012 11:31
Show Gist options
  • Select an option

  • Save bsingr/3394368 to your computer and use it in GitHub Desktop.

Select an option

Save bsingr/3394368 to your computer and use it in GitHub Desktop.
Ampersand tricks in Ruby
#!/usr/bin/env ruby
# Modify all values of an array the same way
# Do you often see code like this?
puts [0.3, 0.5, 0.7].map{|float| float.round} # [0, 1, 1]
# We can do better!
puts [0.3, 0.5, 0.7].map(&:round) # [0, 1, 1]
#!/usr/bin/env ruby
# Wanna sum up the content of an array?
# You have experience in traditional for-loops?
sum = 0
for value in [1, 2, 3]
sum += value
end
puts sum # 6
# You are just a Ruby beginner and start liking #each?
sum = 0
[1, 2, 3].each{|value| sum += value}
puts sum # 6
# You've heard about #inject?
puts [1, 2, 3].inject(0){|sum, value| sum += value} # 6
# Oh, come on!
puts [1, 2, 3].inject(&:+) # 6
#!/usr/bin/env ruby
# Wanna make some predictions?
class ExEarthNewsReporter
def publish location, mission, year
puts "The first manned #{location} landing was in #{year} (#{mission})."
end
# Here is the magic!
def to_proc
Proc.new { |args| self.publish *args; nil}
end
end
[["moon", "Apollo 11", 1969],
["mars", "Mars One", 2023]].each(&ExEarthNewsReporter.new)
#!/usr/bin/env ruby
# subject <=> object
["Is it any good?", " - Yes."].map(&method(:puts))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment