The Ruby Infinite Hash
How to create an infinitely nestable hash that always defaults to a new hash if a key does not map to a value.
Related cards:
Iterating over a Ruby Hash while tracking the loop index
You know each_with_index
from arrays:
['hello', 'universe'].each_with_index do |value, index|
puts "#{index}: #{value}"
end
# 0: hello
# 1: universe
This also works on hashes. However, mind the required synt...
Ruby constant lookup: The good, the bad and the ugly
In Ruby, classes and modules are called constants. This card explains how Ruby resolves the meaning of a constant.
The good
E. g. in the following example, Array
could mean either Foo::Array
or simply Array
:
class Fo...
Ruby: Using the pry debugger in projects with older Ruby versions
In case you want to use pry with an older version of Ruby, you can try the following configurations.
Ruby 1.8.7
Your pry
version must not be greater than 0.9.10
.
gem 'pry', '=0.9.10'
gem 'ruby-debug',...
Security issues with hash conditions in Rails 2 and Rails 3
Find conditions for scopes can be given either as an array (:conditions => ['state = ?', 'draft']
) or a hash (:conditions => { 'state' => 'draft' }
). The later is nicer to read, but has horrible security implications in some versions of Ru...
Ruby Scripts: Select the Ruby version in the shebang
As Bill Dueber has on his blog, you can call rvm
in the shebang to select a Ruby version like this:
#!/usr/bin/env rvm 1.9 do ruby
Standard arguments to do
apply, see $> rvm help do
.
Force net/http to verify SSL certificates
Ruby's net/http is setup to never verify SSL certificates by default. Most ruby libraries do the same. That means that you're not verifying the identity of the server you're communicating with and are therefore exposed to man in the middle attacks...
Heads up: Ruby implicitly converts a hash to keyword arguments
When a method has keyword arguments, Ruby offers implicit conversion of a Hash
argument into keyword arguments. This conversion is perfo...
Ruby, Ruby on Rails, and _why: The disappearance of one of the world’s most beloved computer programmers
Nice article to educate your non-geek girlfriend/boyfriend about the joys of programming.
Ruby: How to collect a Hash from an Array
There are many different methods that allow mapping an Array to a Hash in Ruby.
Array#to_h
with a block (Ruby 2.6+)
You can call an array with a block that is called with each element. The block must return a [key, value]
tuple.
This i...
sstephenson/execjs - GitHub
ExecJS lets you run JavaScript code from Ruby. It automatically picks the best runtime available to evaluate your JavaScript program, then returns the result to you as a Ruby object.