What single line of code does Ruby have?
This article mainly introduces "what single-line code does Ruby have". In daily operation, I believe many people have doubts about what single-line code Ruby has. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "what single-line code does Ruby have?" Next, please follow the editor to study!
1. Each element in the array is multiplied by 2
(1. 10). Map {| n | n * 2}
two。 Summation of elements in an array
(1.. 1000). Inject {| sum, n | sum + n}
Or use the (built-in) Symbol#to_proc syntax, which is available since Ruby 1.8.7:
(1... 1000). Inject (&: +)
Even pass a symbol directly:
(1.. 1000). Inject (: +)
3. Verify that tokens exists in the string
Words = ["scala", "akka", "play framework", "sbt", "typesafe"] tweet = "This is an example tweet talking about scala and sbt." Words.any? {| word | tweet.include? (word)}
4. Read a file
File_text = File.read ("data.txt") 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 using an alternative version:
File.read ("data.txt") .split (/\ n /)
5. Happy birthday
4.times {| n | puts "Happy Birthday # {dear Tony": "to You"}
6. Filter numbers in an array
[49, 58, 76, 82, 88, 90] .partition {| n | n > 60}
7. Get and parse a XML Web service
Require 'open-uri' require' hpricot' results = Hpricot (open ("http://search.twitter.com/search.atom?&q=scala"))
This example requires open-uri or hpricot or equivalent libraries (you can use the built-in if you prefer). There's not much code, but Scala wins out here.
8. Find the minimum (or *) value in the array
[14, 35,-7, 46, 98] .min [14, 35,-7, 46, 98] .max
9. Parallel processing
Require 'parallel' Parallel.map (lots_of_data) do | chunk | heavy_computation (chunk) end
Unlike Scala, multicore support is not built-in. It needs parallel or something like that.
10. Ella Tostney sieving method
Scala's single line of code is smart, but completely unreadable. Although it is not a single line of code here, a simpler implementation can be written with Ruby:
Index = 0 while primes [index] * * 2