# reject elements. Returns the array without the rejected elements. ["", "1", "2"].reject(&:empty?) # Select elements. Returns an array. [10, 2, 1].select { |value| value >= 1 } # Check elements against a condition. Returns a boolean. [132, 12, 0.5].any? { |value| value > 1 } # Select a random element %w(one two three).sample # Sort hashes [{ age: 12, name: "John" }, { age: 21, name: "Betty" }].sort_by { |value_hash| value_hash[:age] } # Count the number of occurences %w(one two three one one).count("one") # > 3 # Split in smaller arrays. Returns an enumerator %w(one two three four five six).each_slice(2) # > [["one", "two"], ["three", "four"], ["five", "six"]] # Make an array out of something. Array.wrap(something)
(1..4).each_with_object([]) { |item, ob| ob << item * 10 } => [10, 20, 30, 40] > (1..4).each_with_object({}) { |i, ob| ob[i] = i * 10 } => {1=>10, 2=>20, 3=>30, 4=>40}
Get all keys recursively in a Hash
def get_all_keys(ha) ha.each_with_object([]) do |(key, value), keys| keys << key keys.concat(get_all_keys(value)) if value.is_a? Hash end end
Directories
Dir.pwd # Current directory Dir.chdir "take_me_home/directory/" # Change directory Dir.glob("*") # Array of files' name in pwd Dir.glob('dir_name/**/*.{avi,m4a}') # Every avi and m4a files, including in sub-directories Dir["/target_directory/*"] # Array of files' path + name
Files
File.basename("my_code.rb")
Nuclear csv parsing: never see the dreaded invalid byte sequence
error ever again
csv_file = File.read(file) .encode("UTF-8", "binary", invalid: :replace, undef: :replace, replace: "") CSV.parse(csv_file, col_sep: ";", force_quotes: true, encoding: "utf-8")
# Execute unix commands using backticks `. Returns a string `wc -l line_count.csv`
require "benchmark" puts Benchmark.measure { "something".capitalize } iterations = 1_000 Benchmark.bm(iterations) do |bm| bm.report "message here" do "something".capitalize end bm.report "another convoluted method" do "something"[0].upcase + "something"[1..-1] end end Benchmark.ips do |x| x.report("any?") { Actor.any? } x.report("limit(1)") { Actor.limit(1).count } x.compare! end # Comparison: # limit(1): 1213.5 i/s # any?: 597.1 i/s - 2.03x slower
Syntax highlighting of other languages from within ruby code
sql_query = <<-SQL SELECT * FROM users WHERE is_awesome IS true SQL
URI Library
URI.parse("http://www.github.com")