Skip to content

Instantly share code, notes, and snippets.

@tanyaschlusser
Last active June 10, 2019 13:12
Show Gist options
  • Save tanyaschlusser/81c527f70736047a78e9ee56e9955f43 to your computer and use it in GitHub Desktop.
Save tanyaschlusser/81c527f70736047a78e9ee56e9955f43 to your computer and use it in GitHub Desktop.
Ruby notes

Summarizing the core Ruby docs and the Ruby koans

Note

  • use gem environment to show all of the search paths
  • Use ri <thing> in the rails console to get documentation on <thing>.
  • Or help "string-version of <thing>" Help so far seems quite good
  • The return value of a function is its last statement unless there is a specific return statement
  • Top level constants are referenced by double colons ::top_level_const which is useful if you have a local variable with the same name.

Style

  • Dot at the end of the line and then continue with two-space indent.

Surprise!

  • O is truthy
  • Single-quote strings do not interpret escaped characters. Nor do they interpolate values.
  • Double-quote strings do. (They also interpolate values--like f-strings in Python) "foo #{bar}"
  • Maybe this is like SQL and not so insane.
  • Careful of the different equals signs (see operators below)
  • (Ruby 2.4 solves this by making one Integer type; May 2019 we are on Ruby 2.6.3 so no worries) Prior to this, if you bitshift a Fixednum and it goes too big, it will magically turn into a Bignum rather than drop the highest bit.

Rails surprise!

  • The test database can be left in a nonpristine state once run. This means it's best to clear it up before running rspec again or you may have randomly failing tests that don't make sense.
bin/rake db:drop RAILS_ENV=test;bin/rake db:create RAILS_ENV=test;bin/rake db:schema:load RAILS_ENV=test
  • In Rails effing every single effing constant is imported like all the effing place. OK great. This blog post explains. To find the order of name resolution, use ActiveSupport::Dependencies.autoload_paths.

Tools

  • rake is like Make but with Ruby language. A Rakefile is like a Makefile.
    • rake -T list all Tasks.
    • rake -W db:create will tell you Where db:create is defined.
  • Interpreter
    • The interactive ruby console is irb
    • There is another one pry that about half the community prefers (cheatsheet)
    • There is a rails console that apparently does import * or something on the entire project into a pry console (?)
  • Testing
    • The standard library includes minitest (unittests; Test Driven Development link)
    • However many people prefer rspec (Behavior Driven Development cheatsheet)
  • Two camps: Javascript / Front End
    • Make Rails a JSON api server and make React the View/Controller part (create-react-app)
    • Keep your flat HTML and sprinkle Javascript (stimulus; DHH preference "don't put your chocolate in my peanut butter")

Operators

  • defined? is the "defined" operator, and returns true if all elements on its right hand side are defined
  • ~ is one's complement
  • % is modulo
  • .. (two dots) and ... (three dots) make a Range of numbers: (0..2).to_a makes [0, 1, 2] but (0...2).to_a makes [0, 1] (seems backwards)
  • ** is exponentiation
  • * is multiplication in math or "splat operator" when unlisting a list (e.g. *args just like Python)
  • ^ is XOR
  • & is bitwise (or array-wise i think too) and, && is boolean and (so is and, with lower precedence) & &:<symbol> is unpack -- it unpacks the symbol :<symbol> and sends that as a literal block. See Stackoverflow -- something {|i| i.foo } and something(&:foo) are equivalent.
  • << is "shovel operator" -- bitshift, append, concatenate Surprise a FIXNUM that is bitshifted higher becomes a BIGNUM (doesn't just drop the top bit)
  • <=> is "spaceship operator" -- a multiple outcome comparator:
    • 1 <=> 0 returns 1
    • 1 <=> 1 returns 0
    • 1 <=> 2 returns -1
    • 1 <=> 'hello' returns nil
  • == is, === is .. there are four equals
    • == True by default if lhs and rhs are the same object, but typically overridden to have expected meaning
    • != is the opposite of whatever == is
    • === case equality...see the stackoverflow link...can mean stuff like "lhs is in the range of rhs" or "lhs matches the regex rhs" or even the outcome of rhs(lhs) (rhs a lambda function)
    • equal? True if lhs and rhs are the same object (cannot be overridden)
    • eql? True if lhs and rhs hash to the same thing (can be overridden)
  • =~ is the pattern matching operator; returns nil or the number in the string where the Regexp pattern matches
  • | is bitwise (or array-wise) or, || is boolean or (you can also use or which has lower precedence)

Symbols

  • __ (single underscore) is a discarded variable placeholder.
  • $1, $2, $3 are the first, second, and third group items in the most recently evaluated Regexp.
  • __FILE__ is absolute path of current actual file
  • ClassName#method_name -- the hash is for an instance method
  • ClassName::method_name -- the double colons are for a class method

Classes

  • Object — the default root of all Ruby objects
  • Array — Array
  • Hash — dictionary-like collection,
    • e.g. with symbols (typical) {:a => 1, :b => 2} or {a: 1, b: 2}
    • or strings {"a" => 1, "b" => 2}
    • NOTE THAT STRINGS DO NOT EVALUATE TO SYMBOLS
  • Proc — blocks of code bound to a local variable
  • Range — e.g. 1..5 (inclusive) or 1...5 (excludes 5)
  • Regexp — e.g. /a [Regxp]/
  • String — e.g. "a_string"
  • Symbol — e.g. :a_symbol (immutable)

Concepts

  • Mixins exist. Not 100% sure about multiple inheritance.
  • Switch statements exist
  • Actual private variables exist. All class attributes are by default private unless you write an accessor

Environment

  • rbenv and rvm: different people use different ones; sets the version of Ruby
  • bundler: everyone uses it; does version resolution for dependencies and creates an isolated install environment for the app

Rails ORM

  • scope :symbol, -> { # qualifiers } will restrict the scope of a query according to the qualifiers in the block
  • When is the query actually called for ActiveRecord? Good answer on StackOverflow

Rails other stuff

Rails community stuff

  • DHH stands for David Heinemier Hansson (who according to Obie Fernandez (hashrocket; "The Rails # Way") hates the abbreviation even though it's his twitter handle)
  • Unicorn was the prior darling web server now it's Puma (because threading?) for pretty much everyone
  • Rails 4.X support was dropped in March 2017 and security updates are rumored to be dropped as soon as 6.0 is stable which is anticipated within months (it's May 2019) because the RC1 was out for RailsConf.
  • Rails 5 has ActiveCable (sockets?)
  • Rails 6 has ActiveStorage (uploads?)
  • Not like you couldn't do the above before. just now there's a preferred library.

Vocabulary

  • Lexical scope
  • Inheritance Hierarchy
  • Module vs Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment