Skip to content

Instantly share code, notes, and snippets.

@joseluistorres
Created February 27, 2017 16:25
Show Gist options
  • Save joseluistorres/97ff6365af6cc8163a0f2c677d119206 to your computer and use it in GitHub Desktop.
Save joseluistorres/97ff6365af6cc8163a0f2c677d119206 to your computer and use it in GitHub Desktop.
Cheat Sheet Ruby operations

Slice an array

arr_new = arr_new.slice(0, len - 1)

Insert a new item at the begginning of the array

arr_new.unshift(last_item)

Find number of occurrences of a substring in a string

str.scan(/(?=#{sample})/).count

Parse a String for CSV

CSV.parse(csv_string) do |row|
end

Sort an array of hashes by a value

# ascending
script_per_week = script_per_week.sort_by { |k| -k[:scripts_per_week] }
# descending
script_per_week = script_per_week.sort_by { |k| k[:scripts] }

Flattenning an array of arrays

def flatten_it(arr)
  arr.each_with_object([]) do |e, flattening|
    flattening.push *(e.is_a?(Array) ? flatten_it(e) : e)
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment