csv
raw_data = File.read('')
#Appropriately parse csv that is invalid in RFC4180 compliant parsing (CSV parser specification of ruby standard library)
parsed_csv = CSV.parse(raw_data, col_sep: "\t", liberal_parsing: true)
array
#Union(Duplication is removed)
p a | b
# a,Add b and put in a new array
p a + b
#Difference set
p a - b
#Intersection
p a & b
Enumerable Extraction
#Extract only the elements whose expression in the block is true
#Empty array if no element is true
[1, 2, 3, 4, 5, 6].select {|n| n % 2 == 0 }
#Hash is also possible
{:a => 1, :b => 2}.select {|k, v| v == 1 }
#Returns the first element whose expression in the block is true
#nil if no element is true
[1, 5, 8, 2, 6, 3].find {|n| n % 3 == 0 }
#Extract only the elements whose expression in the block is false
[1, 2, 3, 4, 5, 6].reject {|n| n % 2 == 0 }
#Extract only the elements that match the argument (regular expression is possible)
#Empty array if there are no matching elements
['a1', 'bb', 'c2', 'dd', '5e'].grep(/[0-9]/)
Value manipulation
#Returns the result of executing the expression in the block for each element
[1, 2, 3].map {|n| n * 3 }
#Execute the expressions in the block sequentially for each element
#result contains the last evaluated value in the block
[1, 2, 3, 4, 5].inject(10) {|result, item| result + item }
#Execute the expressions in the block sequentially for each element
#result always points to the object passed as an argument (cannot be destructively modified)
[["Alice", 50], ["Bob", 40], ["Charlie", 70]].each_with_object({}) {|(key, value), result| result[key] = value }
#Returns a hash with the result of the expression in the block as the key and the array of corresponding elements as the value
# => {1 => [1, 3, 5], 0 => [2, 4, 6]}
[1, 2, 3, 4, 5, 6].group_by {|i| i % 2 }
#The result of the expression in the block<=>Returns the result of comparing by operator and sorting in ascending order
p ["foo", "bar", "Baz", "Qux"].sort_by { |v| v.downcase }
#This way you can sort the numbers in descending order
p [1, 5, 7, 2, 4, 9].sort_by { |v| v * -1 }
date.match?(%r(\A\d{4}/\d{2}/\d{2}\Z))
#Parse the date and time from a string
#UTC, ignoring the Rails configuration timezone
DateTime.parse('2015-10-01 00:00:00')
Recommended Posts