Ruby Reference

Kip Landergren

(Updated: )

My cheat sheet for the Ruby programming language

Contents#

Documentation#

FAQ#

How do I run a specific version of a gem?#

$ my-gem _x.y.x_ [args]

What is the RubyGems error ... is not an octal string related to?#

AKA: “Why am I getting ... is not an octal string when running gem push?”

I encountered this when I was incorrectly pushing the .gemspec, rather than the .gem.

When publishing to RubyGems you should:

$ cd path/to/my-gem
$ gem build my-gem
$ gem push my-gem-0.0.1.gem

Terminology#

hash rocket (=>)#
1.

Key / value separator in a hash literal.

foo = { "name" => "bar"}

Note: Used in hashes, looks like a rocket.

pessimistic operator (~>)#
1.

Used in version constraints to indicate the highest version acceptable, according to semantic versioning rules.

Example:

source "https://rubygems.org"
gem "nokogiri", "~> 1.9.0" # equivalent to: gem "nokogiri", ">= 1.9.0", "< 1.10.0"

Also: twiddle wakka

Note: The nickname ”twiddle wakka” comes from:

“twiddle” another name for the tilde (according to the Jargon File entry )
“wakka” possibly due >’s similarity to Pac Man and his sound when eating dots

More info in the Medium Article The Strange Case of the Twiddle Wakka.

spaceship operator (<=>)#
1.

General comparison method.

a <=> b returns:

-1 a is less than b
0 a equals b
1 a is greater than b
nil the two can’t be compared

Note: Looks like a spaceship.

ruby-study#

.ruby-version#

3.1.3

README.md#

# ruby-study

Personal study area for the latest version of [ruby](https://www.ruby-lang.org/en/).

core/hash/delete.rb#

# hash delete key
h = {a: 1, b: 2}
h.delete(:a)

core/hash/dig.rb#

# hash find within nested object
h = {foo: { bar: { baz: -1}}}
h.dig(:foo)
h.dig(:foo, :bar)
h.dig(:foo, :bar, :baz)
h.dig(:foo, :qux)

core/hash/transform_keys.rb#

# hash convert symbol keys to strings
h = {foo: "bar"}
h_transformed = h.transform_keys {|k| k.to_string }

# perform transform keys in-place
h.transform_keys! {|k| k.to_string }

core/hash/transform_values.rb#

# hash transform values
h = {a: 1, b: 2}.transform_values {|v| v * v }

# perform transform values in-place
h.transform_values! {|v| v * v }

core/io/read.rb#

# read file as string
contents = IO.read('path/to/file.txt')

core/io/readlines.rb#

# read lines of file, using `chomp: true` to omit newlines
lines = IO.readlines('path/to/file.txt', chomp: true)

core/string.rb#

# strip (trim)
s1 = "  foo\n ".strip

# strip! (trim)
input1 = "  foo\n "
input1.strip!

std-lib/set.rb#

require 'set'

s1 = Set[1,2]
s2 = [1,2].to_set