Created
July 1, 2011 10:05
-
-
Save ouyangzhiping/1058219 to your computer and use it in GitHub Desktop.
10 Ruby One Liners to Impress Your Friends
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#10 Ruby One Liners to Impress Your Friends | |
#http://programmingzen.com/2011/06/02/10-ruby-one-liners-to-impress-your-friends/ | |
#1. Multiply each item in a list by 2 | |
p (1..10).map {|n| n*2} | |
#2.Sum a list of numbers | |
p (1..1000).inject { |sum, n| sum + n } | |
#Or using the (built in) Symbol#to_proc syntax that’s been available since Ruby 1.8.7: | |
p (1..1000).inject(&:+) | |
#Or even just passing a symbol directly: | |
p (1..1000).inject(:+) | |
#3. Verify if tokens exist in a string | |
words = ["scala", "akka", "play framework", "sbt", "typesafe"] | |
tweet = "This is an example tweet talking about scala and sbt." | |
p words.any? { |word| tweet.include?(word) } | |
#4. Reading a file | |
p file_text = File.read("data.txt") | |
p file_lines = File.readlines("data.txt") | |
#The latter includes “\n” at the end of each element of the array, which can be trimmed by appending .map { |str| str.chop } or by using the alternative version: | |
p File.read("data.txt").split(/\n/) | |
#5. Happy Birthday | |
4.times { |n| puts "Happy Birthday #{n==2 ? "dear Tony" : "to You"}" } | |
#6. Filter a list of numbers | |
p [49, 58, 76, 82, 88, 90].partition { |n| n > 60 } | |
#7.Fetch and parse an XML web service | |
require 'rubygems' | |
require 'open-uri' | |
require 'hpricot' | |
results = Hpricot(open("http://www.google.com/search?q=ruby")) | |
#p results | |
#8.Find minimum (or maximum) in a list | |
p [14, 35, -7, 46, 98].min | |
p [14, 35, -7, 46, 98].max | |
#9. Parallel Processing | |
require 'rubygems' | |
require 'parallel' | |
Parallel.map(lots_of_data) do |chunk| | |
heavy_computation(chunk) | |
end | |
#10. Sieve of Eratosthenes | |
#http://zh.wikipedia.org/wiki/%E5%9F%83%E6%8B%89%E6%89%98%E6%96%AF%E7%89%B9%E5%B0%BC%E7%AD%9B%E6%B3%95 | |
n=120 | |
primes = Array.new | |
for i in 0..n-2 | |
primes[i] = i+2 | |
end | |
index = 0 | |
while primes[index]**2 <= primes.last | |
prime = primes[index] | |
primes = primes.select { |x| x == prime || x%prime != 0 } | |
index += 1 | |
end | |
p primes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment