{"id":13516198,"url":"https://github.com/O-I/Facets","last_synced_at":"2025-03-31T06:30:29.155Z","repository":{"id":12426642,"uuid":"15082105","full_name":"O-I/Facets","owner":"O-I","description":"A community-curated list of one-liners in Ruby","archived":false,"fork":false,"pushed_at":"2015-10-19T02:52:48.000Z","size":190,"stargazers_count":15,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-11-01T20:36:18.063Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/O-I.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-12-10T16:09:12.000Z","updated_at":"2024-09-22T03:56:47.000Z","dependencies_parsed_at":"2022-09-23T06:51:34.960Z","dependency_job_id":null,"html_url":"https://github.com/O-I/Facets","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/O-I%2FFacets","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/O-I%2FFacets/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/O-I%2FFacets/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/O-I%2FFacets/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/O-I","download_url":"https://codeload.github.com/O-I/Facets/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246429459,"owners_count":20775805,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T05:01:20.162Z","updated_at":"2025-03-31T06:30:28.888Z","avatar_url":"https://github.com/O-I.png","language":null,"readme":"Facets\n======\n\nA community-curated list of one-liners (or several-liners if elegance demands) in Ruby\n\n### Files, Folders, and Paths\n\n##### Convert the contents of `filename` to a string\n```ruby\nFile.open(filename, 'rb') { |file| file.read }\n```\n\n##### Get the current user's home directory\n```ruby\nDir.home\n```\n\nThis only works if `ENV['HOME']` is set, though. RubyTapas #10 gives us an alternative using `Etc` to find the current user's login name and passing that to `Dir.home`:\n```ruby\nDir.home(Etc.getlogin)\n```\n\n### Strings\n\n##### Calculate the Hamming distance between two strings `str1` and `str2` (returns `nil` if `str1` and `str2` are of unequal length):\n```ruby\nstr1.chars.zip(str2.chars).reduce(0) { |sum, (x, y)| sum + (x == y ? 0 : 1) } if str1.size == str2.size\n```\n\n##### Determine whether one string `str1` is a rotation of another string `str2`:\n```ruby\n(str1 + str1)[str2] == str2\n```\n\n##### Get the `n`th bit of an `Integer` `j`:\n\nMy first inclination would be to convert to binary and use `[]`, i.e., `j.to_s(2)[n].to_i`, but you can call `[]` directly on an `Integer`:\n```ruby\nj[n]\n```\n\n### Arrays\n\n##### Remove all instances of value `l` from an array `a` and return the result\n```ruby\na - [l]\n```\n\nOr `a -= [l]` if you would like to reasign the result to `a`. This is the most elegant way I've seen of doing this. Doing something like `a.delete(l)` returns `l` rather than the updated value of `a` which disrupts method chaining. You could always do `a.tap { |x| x.delete(l) }`, but I think the above line is superior and just as chainable if enclosed in parentheses.\n\n##### Convert an array `a` with even index whose elements are alternating key value pairs (e.g., `[k1, v1, k2, v2,..., kn, vn]` into the respective hash `h`\n```ruby\nh = Hash[*a]\n```\nThis is likely not a good idea if `a` happens to be a large dataset as the splat operator will expand all contents of the array to the stack. In that case, you can use `h = Hash[a.each_slice(2).to_a]`.\n\nIn the event `a` is already a 2D array of the form `[[k1, v1], [k2, v2],..., [kn, vn]]`, you can simply do `h = Hash[a]`. And from Ruby 2.1 onwards, you can simply use `Array#to_h`: `h = a.to_h`.\n\n##### Create an `n`x`n` multiplication table represented by a 2-dimensional array:\n```ruby\n[*1..n].product([*1..n]).map { |arr| arr.reduce(:*) }.each_slice(n).to_a\n```\nOr, if you're using ActiveSupport:\n```ruby\n[*1..n].product([*1..n]).map { |arr| arr.reduce(:*) }.in_groups(n)\n```\n\nAnd in terms of clarity, this one's about as good as it gets:\n```ruby\nArray.new(n) { |x| Array.new(n) { |y| (x+1)*(y+1) } }\n```\n\n##### Calculate the frequency distribution of an array `a`:\n\nThere are many ways to do this, but using `Enumerable#each_with_object` seems to be the most idiomatic:\n```ruby\na.each_with_object(Hash.new(0)) { |element, frequency| frequency[element] += 1 }\n```\n\n`Enumerable#reduce` also works, but feels clumsier. Notice that the block parameters are reversed compared to the above and the need to explicitly return the accumulator on each pass:\n```ruby\na.reduce(Hash.new(0)) { |frequency, element| frequency[element] += 1; frequency }\n```\n\nAnd yet another way using Ruby 2.2+ that seems truest to a functional style:\n```ruby\na.group_by(\u0026:itself).map { |k, v| [k, v.size] }.to_h\n```\n\n##### Get all but the first element of an array `a`:\n\nYou can use parallel assignment in conjunction with the splat operator if you're planning on using the head:\n```ruby\nhead, *rest = a\n```\n\nBut if you just want the rest, using `drop` is better:\n```ruby\na.drop(1)\n```\n\nBoth are preferable to `a[1..-1]` in that they return `[]` rather than `nil` if `a` is empty.\n\n##### Find all duplicate values in an array `a` (Ruby 2.2+):\n```ruby\na.group_by(\u0026:itself).select { |_, v| v.size \u003e 1 }.keys\n```\n\nYou can replace `group_by(\u0026:itself)` with `group_by { |n| n }` for lesser versions of Ruby.\n\n##### Calculate rolling averages of an array `a` over interval length `n`:\n```ruby\na.each_cons(n).map { |interval| interval.reduce(:+) / n.to_f }\n```\n\n##### Reduce an array `a` of Boolean values\n\nFor *and*, *or*, and *xor*, we can use `Enumerable#reduce` paired with the appropriate logical operator, i.e., `a.reduce(:\u0026)`, `a.reduce(:|)`, and `a.reduce(:^)`, respectively.\n\nFor reducing over *and* and *or*, I find `a.all?` and `a.any?` to be more idiomatic than explicit use of `reduce`.\n\n##### \"Map compact\" or \"select map\"\n\nThis one is best illustrated by an example. Note, I don't think there is a particularly elegant way to do what I'm about to describe in Ruby. A common idiom is to map over a collection and select the resulting values for those elements which conform to some predicate.\n\nFor example, suppose we have an array `a = [1, 2, 3, 4, 5]` and want to get a resulting collection that adds 1 to each element only if that element is even. We can achieve this in several ways:\n\n```ruby\na = [1, 2, 3, 4, 5]\n\na.map { |l| l + 1 if l.even? }.compact                      # =\u003e [3, 5]\na.select(\u0026:even?).map { |l| l + 1 }                         # =\u003e [3, 5]\na.each_with_object([]) { |l, res| res \u003c\u003c l + 1 if l.even? } # =\u003e [3, 5]\na.reduce([]) { |res, l| res.push(l + 1) if l.even?; res }   # =\u003e [3, 5]\n```\n\nAll of these one-liners return the desired result, all of them feel clumsy.\n\n### Hashes\n\n##### Create a hash `h` from two arrays `k` and `v` of equal length that represent `h`'s keys and values, respectively:\n```ruby\nh = Hash[k.zip(v)]\n```\n##### Decompose a hash `h` into two arrays `k` and `v` that respresent `h`'s keys and values, respectively:\n\n1) The straightforward way:\n```ruby\nk, v = h.keys, h.values\n```\n2) Or more cryptically for impressing your nerdy friends:\n```ruby\nk, v = *h.to_a.transpose\n```\n\n##### Remove key-value pairs in hash `h` given keys in array `a`:\n\nActiveSupport has a nifty little method for this called `Hash#except`. The best I could come up with for doing this in one line with Ruby non-destructively is\n```ruby\nhash.tap { |h| a.map { |k| h.delete(k) } }\n```\n\n##### Weighted random sampling without replacement of a hash `h`'s keys whose values are weighted probabilities that sum to 1:\n```ruby\nh.max_by { |_, weight| rand ** (1.0/weight) }.first\n```\n\nThis is essentially the weighted analogue of `Array#sample`. With Ruby 2.2+, we also have the analogue of `Array#sample(n)`:\n```ruby\nh.max_by(n) { |_, weight| rand ** (1.0/weight) }.map(\u0026:first)\n```\n\n### Regular Expressions\n\n### Calculations\n\n##### Compute `n!` for all nonnegative integers n (returns `nil` otherwise):\n\n```ruby\n(1..n).reduce(1, :*) if n.is_a?(Integer) \u0026\u0026 n \u003e -1\n```\n\n### Miscellaneous\n\n##### Given an `m`x`n` matrix, return an array that represents the clockwise spiral path from the top left to the center. For example, given\n\n    matrix = [[1,2,3],\n              [8,9,4],\n              [7,6,5]]\n              \n`spiral(matrix)` should return `[1, 2, 3, 4, 5, 6, 7, 8, 9]`\n\n```ruby\ndef spiral(matrix)\n  matrix.empty? ? [] : matrix.shift + spiral(matrix.transpose.reverse)\nend\n```\n\nNote that this implementation has one major drawback — it mutates its argument.\n\n##### `Symbol#to_proc` with arguments\n\nThis isn't a one-liner nor is it something I recommend without extreme caution as it patches a core class, but it is one of the slickest — if not the slickest — Ruby hacks I've ever seen.\n\nOpen up the `Symbol` class and add a `call` method to it that contains the following lambda:\n\n```ruby\nclass Symbol\n  def call(*args, \u0026block)\n    -\u003e(caller, *rest) { caller.send(self, *rest, *args, \u0026block) }\n  end\nend\n```\n\nThis gives `Symbol#to_proc` the superpower of accepting arguments. so, instead of doing, e.g.,\n\n```ruby\nnums = [1, 2, 3, 4]\ntext = %w(this is a test)\n\nnums.map { |num| num ** 1i }\ntext.map { |word| word.gsub('s', '*') }\n```\n\nwe can do\n\n```ruby\nnums.map(\u0026:**.call(1i))\ntext.map(\u0026:gsub.call('s', '*'))\n```\n\nBut there's one more trick here. By naming our method `call`, we can use the shorter `.()` syntax:\n\n```ruby\nnums.map(\u0026:**.(1i))\ntext.map(\u0026:gsub.('s', '*'))\n```\n","funding_links":[],"categories":["Technical"],"sub_categories":["ramanihiteshc@gmail.com"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FO-I%2FFacets","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FO-I%2FFacets","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FO-I%2FFacets/lists"}