{"id":23333868,"url":"https://github.com/schultyy/ruby-cheatsheet","last_synced_at":"2026-03-20T01:12:36.554Z","repository":{"id":137289314,"uuid":"12372182","full_name":"schultyy/ruby-cheatsheet","owner":"schultyy","description":null,"archived":false,"fork":false,"pushed_at":"2014-02-04T12:30:42.000Z","size":172,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-10-09T03:58:35.592Z","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/schultyy.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-08-26T05:54:29.000Z","updated_at":"2022-07-29T06:17:17.000Z","dependencies_parsed_at":"2023-03-11T19:30:12.013Z","dependency_job_id":null,"html_url":"https://github.com/schultyy/ruby-cheatsheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/schultyy/ruby-cheatsheet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/schultyy%2Fruby-cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/schultyy%2Fruby-cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/schultyy%2Fruby-cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/schultyy%2Fruby-cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/schultyy","download_url":"https://codeload.github.com/schultyy/ruby-cheatsheet/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/schultyy%2Fruby-cheatsheet/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28562405,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-19T03:31:16.861Z","status":"ssl_error","status_checked_at":"2026-01-19T03:31:15.069Z","response_time":67,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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-12-21T00:32:38.317Z","updated_at":"2026-01-19T06:33:17.445Z","avatar_url":"https://github.com/schultyy.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# ruby-cheatsheet\n\n## Delegators\n\n```Ruby\n  class Engine\n    attr_accessor :horse_powers\n    def initialize(hp)\n      @horse_powers = hp\n    end\n  end\n  \n  class Car\n    def_delegator :@engine, :hp, :horse_powers\n  \n    def initialize()\n      @engine = Engine.new\n    end\n  end\n```\n\n## Strings\n\n### Test if string is empty\n\n```Ruby\n\tfoo.empty?\n```\n\t\n## Iterators\n\n```Ruby\n    a_list.each do |item|\n      #Inside of block\n      #we can work with item\n    end\n```\n\n## object_id\n\nThe `object_id` method returns the identity of an object. If two objects have the same `object_id`, they are the same (point to the same Object in memory).\n\n## Symbols\n\n    \u003e :george.object_id == :george.object_id\n    =\u003e true\n    \u003e \"george\".object_id == \"george.object_id\n    =\u003e false\n\nSymbols are identities (IDs). It is important *who* it is not *what* it is.\nA symbol with the same characters references the same Object in memory. For any given two Symbols that represent the same characters, the `object_id`s match.\n\nIf in doubt wheter to use a Symbol or a String, consider what's more important: the identity of an object (i.e. Hash key), or the contents (in the example above, \"george\").\n\n## Naming conventions\n\n* Constant: Starts with capital letter\n* $: global variable\n* @: instance variable\n* @@: class variable\n\nMethod names are allowed to start with capital letters:\n\n```Ruby\n    Constant = 10\n    def Constant\n        11\n    end\n    puts Constant   #10\n    puts Constant() #11\n```\n\n## Keyword arguments (Ruby 2.0)\n\n```Ruby\n    def deliver(from: 'A', to: nil, via: 'mail')\n        \"Sending from #{from} to #{to} via #{via}.\"\n    end\n    \n    \u003e deliver(to: 'B')\n    =\u003e \"Sending from A to B via mail.\"\n    \u003e deliver(via: 'Pony Express', from: 'B', to: 'A')\n    =\u003e \"Sending from B to A via Pony Express.\"\n```\n\n## The universal truth\n\nEverything except `nil` and `false` is considered `true`.\n\n```Ruby\n    if 0\n        puts \"0 is true\"\n    else\n        puts \"0 is false\"\n    end\n    \n    #0 is true\n```\n\n## Message passing, not functions calls\n\nA method call is really a *message* to another object:\n\n```Ruby\n    1 + 2\n    # is the same like\n    1.+(2)\n    # Which is the same as this:\n    1.send \"+\", 2\n```\n\n## Get all instance methods\n\n### Returns all methods\n```Ruby\n    \u003e Greeter.instance_methods\n    =\u003e [\"method\", \"send\", \"object_id\", ...]\n```\n### Returns only instance methods\n```Ruby\n    \u003e Greeter.instance_methods(false)\n    =\u003e [\"say_hello\", \"say_goodbye\"]\n```\n### Check if an object responds to a method\n```Ruby\n    \u003e g.respond_to?(\"foo\")\n    =\u003e false\n```\n\n### Duck typing\n```Ruby\n    def say_goodbye\n        if @names.nil?\n            puts \"...\"\n        elsif @names.respond_to?(\"join\")\n            #Check if names respond to types. Here the actual type of @names does not matter\n            puts \"Cia, #{@names.join(\", \")}\n        else\n            puts \"Ciao #{@names}\"\n        end\n    end\n```\n### Entry point for scripts\n\n```Ruby\n    if __FILE__ == $0\n    end\n```\n\n## Parse Yaml files\n\n```Ruby\n    require 'yaml'\n    \n    config = YAML.load_file('config.yml')\n    puts config.inspect\n```\n\n## Shell Commands\n\n### Exec\nReplaces the current process by running the given command. \n\n```Bash\n    $ irb\n    \u003e\u003e exec 'echo \"hello $HOSTNAME\"'\n    hello nate.local\n    $\n```\n\n### System\nThe `system` command operates similarly but runy in a subshell instead of replacing the current process.\n`system` returns a little more information than `exec` in that it returns `true` if the command ran successfully or `false` otherwise.\n\n```Bash\n\n    $ irb\n    \u003e\u003e system 'echo \"Hello $HOSTNAME\"'\n    hello nate.local\n    =\u003e true\n    \u003e\u003e system 'false'\n    =\u003e false\n    \u003e\u003e puts $?\n    256\n    =\u003e nil\n    \u003e\u003e\n```\n\n`system` sets the global variable `$0` to the exit status of the process. Notice that we have the exit status of \nthe `false` command (which always exits with a non-zero code). \n\n\u003e Note: Unix commands typically exit with a status of `0` on success and non-zero otherwise.\n\n### Backticks(`)\n\nBackticks (also called \"backquotes\") runs the command in a subshell and returns the standard output from that command.\n\n```Bash\n    $ irb\n    \u003e\u003e today = `date`\n    =\u003e \"Monday...\"\n    \u003e\u003e $?\n    =\u003e #\u003cProcess::Status: pid=25827, exited(0)\u003e\n    \u003e\u003e $?.to_i\n    =\u003e 0\n```\n\n\u003e Note: `$?` is not simply an integer of the return status but actually a `Process::Status` object.\n\nOne consequence of using backticks is that only *standard output* (`stdout`)  of this command is available but not `stderr`.\n\n## Classes\n\n### attr_accessor\n\nLet's say there is a class `Person`:\n\n```Ruby\n\n    class Person\n    end\n    \n    person = Person.new\n    person.name # =\u003e no method error\n\n```\n\nObviously we never defined method `name`. Let's do that.\n\n```Ruby\n\n    class Person\n        def name\n            @name #Simply returning an instance variable @name\n        end\n    end\n\nperson = Person.new\nperson.name # =\u003e nil\nperson.name = \"Boo\" # =\u003e no method error\n\n```\n\nWe can read the name but that doesn't mean we can assign a name. Former called **reader** and latter called **writer**. Let's create a writer:\n\n```Ruby\n\n\tclass Person\n\t\tdef name\n\t\t\t@name #Returns instance variable @name\n\t\tend\n\t\t\n\t\tdef name=(str)\n\t\t\t@name = str\n\t\tend\n\t\t\n\t\tperson = Person.new\n\t\tperson.name = \"Boo\"\n\t\tperson.name # =\u003e \"Boo\"\n\tend\n```\n\nNow we can read and write instance variable `@name` using reader and writer methods. Except, this is done so frequently, why waste time writin these methods every time? We can do it easier.\n\n```Ruby\n\t\n\tclass Person\n\t\tattr_reader :name\n\t\tattr_writer :name\n\tend\n\t\n```\n\nEven this can get repetitive. When you want both reader and writer just use accessor!\n\n```Ruby\n\n\tclass Person\n\t\tattr_accessor :name\n\tend\n\t\n\tperson = Person.new\n\tperson.name = \"Boo\"\n\tperson.name # =\u003e \"Boo\"\n\n```\n\n## irb\n### Reload file in irb\n\n```irb\n\u003e\u003e load 'myfile.rb'\n```\n\n## Filesystem\n\n### Get absolute path of a file\n\n```Ruby\n  require 'pathname'\n  \n  abspath = Pathname.new(\"my_fancy_file.txt\")\n  puts abspath.realpath.to_s\n```\n\n### Get filename from path\n\n```Ruby\n  require 'pathname'\n  basename = Pathname.new(\"/opt/local/bin/ruby\").basename\n  basename == \"ruby\"\n```\n\n### Combine pathnames\n```Ruby\n  File.join(\"/Users/John/Foo\", \"Bar\", \"Baz\")\n```\n\n### Strip file extensions\n```Ruby\n  def strip_file_ext(filename)\n    filename.chomp(File.extname(filename))\n  end\n```\n\n## Exception handling\n\n### Basic handling\n\n```Ruby\n  def foo\n    begin\n      #....\n    rescue\n      #Exception handling goes here\n    end\n  end\n```\n\n### Get the exception object\n\n```Ruby\n  def foo\n    begin\n      #....\n    rescue Exception =\u003e e\n      #Exception handling goes here\n    end\n  end\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fschultyy%2Fruby-cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fschultyy%2Fruby-cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fschultyy%2Fruby-cheatsheet/lists"}