Skip to content

Instantly share code, notes, and snippets.

@kyledinh
Last active June 6, 2018 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyledinh/46c08a7b052df5a948f68035c840f802 to your computer and use it in GitHub Desktop.
Save kyledinh/46c08a7b052df5a948f68035c840f802 to your computer and use it in GitHub Desktop.

Interactive Ruby Interface

  • irb
  • load file into IRB irb -r "./some_file.rb"
  • irb> load ".some_file.rb"

Escape codes

\n
\t
\"
\'

answer = gets
p answer       # "enteredstring\n"

sprintf("%0.2f", @transaction[:amount].to_s)
ljust()
rjust()
clean_str = string.gsub("-", "")   # removes dashes
array.includes?

Math.sqrt(9)

Arrays

list = %w(milk eggs bread)    # ["milk", "eggs", "bread"]
item = "celery"
list = %W(#{item} bread)      # ["celery", "bread"]
puts list.inspect             # outputs list
.push and .unshift or += [] or <<
list.insert(2, "item")
list.includes?("celery")
list.drop(2)     # doesnt mutate gives last 2
list.slice(x,y)

arr = [1,2,3,4,7,88]
even_arr = arr.select { |item| item % 2 == 0 }
sml_arr = arr.reject { |item| item > 10 }
arr.inject(0) { |sum, element| sum += element }   # reduce

Classes

  • instantiate str = String.new("some string") initialize method
  • str.class = String
  • str.methods.sort
  • obj.respond_to? :method
module Tracking
  def create(name)
    object = new(name)
    instances.push(object)
    return object
  end
  def instances
    @instances || = []
  end
end

module SuperGroup
  def self.included(klass)
    klass.extend(Enumerable)
    attr_accessor :id, :count
  end
  def fetch(item)
    @count || = 0
    @count += 1
    puts "#{klass} count: #{@count}"
  end
end


class Group
  include Comparable
  #include Enumerable
  include SuperGroup
  extend Tracking
  attr_reader :name, :title
  attr_writer :name
  attr_accessor :desc

  def <=>(other_contact)
    name <=> other_contact.name
  end

  def each(&block)
    contacts.each(&block)
  end

  def initialize(name)
    @name = name
  end

  def name=(new_name)
    @name = new_name
    @conacts = []
  end
end  

Hashes

  • new hash hash = {key: "val", key2: 33}
  • hash[:key2]
  • get all keys hash.keys
  • contains a key `hash.has_key?("some_key")
  • get value for key hash.fetch("some_key")
  • add to has hash.store("new_key", new_val)
  • contains a value hash.has_value?("value")
  • get array of values hash.values_at("k1", "k2") # [val1, val2]
  • for toString hash.inspect
  • get the inverse hash.invert
  • merge hash.merge(hash2)

Iterators

  • times 5.times do |i|
  • range for item in 1..10 do

Object methods

  • show the available methods p "AA".methods.sort
  • show the class p "AA".class gets String
  • Duplicate an object Obj.dup

Convert types

str = "453"
int = str.to_i
float = "123.23".to_f

Rails

bin/rails generate scaffold NewClass field1:string field2:string
bin/rails db:migrate
bundle exec rake db:migrate

Files

append a file

File.open("somefile.txt", "a+") do |file|
end

Standard Library

  • Date, Time
  • hash = JSON.parse(somejson)
  • json_str = JSON.dump(hash)
  • JSON.load( File.new("./file.json") )
  • str = YAML.dump(hash)
  • hash = YAML.load(str)
  • `hash = YAML.load_file("example.yml")``
  • encoded = Base64.encode64(message)
  • url_encoded = Base64.urlsafe_encode64(url)
  • message = Base64.decode64(encoded)
  • logger - Logger.new("log.txt")
  • logger.info "some message"

Gems

  • rubygems.org
  • ruby-toolbox.com
  • gem install [name of gem]
  • gem list
  • gem environment
  • gem content [name of gem]

Creating a New Rails App

  • gem install rails -v 3.2.16
  • rails new digester --database=postgresql
  • gem install activerecord-postgresql-adapter

Creating the Database

  • In PSQL: create user digester with superuser
  • ALTER USER digester WITH SUPERUSER
  • \du \l
  • rake db:create

Create Active Record Associations

  • rails generate model Comment content:text name:string
  • rails generate migration AddPostToComments post_id:integer:index
  • Owner.first.pets.create(name: "Fluffy").save
  • rails generate migration CreateJoinTableUsersForums users forums
  • Uncomment index in ~_create_join_table_users_forums.rb
  • rails generate model Profile user:references twitter:string github:string

erb

  • <%= render partial: "comments/comment", collection: @post.comments, as: :comment %>
  • <%= render @post.comments %> renders views/comments/_comment.html.erb

Rails Console

  • bin/rails console
  • get all records Someclass.all
  • get most recent record Someclass.last
  • get by ID 27 Someclass.where(id: 66)
  • create new object employee = Employee.new
  • delete record Employee.find(25).destroy

Rails Command

  • bin/rails server
  • bin/rails generate scaffold Post title:string
  • bin/rails|rake db:migrate
  • bin/rails generate migration AddBodyToPosts body:text
  • rake db:migrate
  • Get Routes rake routes for rails 3.2.16
  • Controller generate|destroy rails generate controller Pages
  • Model generate rails generate model Page title:string body:text slug:string
  • bin/rails|rake db:migrate

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment