{"id":3670,"date":"2015-04-08T20:46:34","date_gmt":"2015-04-09T00:46:34","guid":{"rendered":"http:\/\/webninjataylor.com\/library\/?p=3670"},"modified":"2015-04-22T14:13:24","modified_gmt":"2015-04-22T18:13:24","slug":"ruby-on-rails-introduction-to-ruby","status":"publish","type":"post","link":"https:\/\/webninjataylor.com\/library\/ruby-on-rails-introduction-to-ruby\/","title":{"rendered":"Ruby on Rails: Introduction to Ruby"},"content":{"rendered":"<ul>\n<li><span class=\"code\">ruby -v<\/span> to check version<\/li>\n<li>Everything in Ruby is an object<\/li>\n<li>You don\u2019t declare variable types, but all objects have a type<\/li>\n<li>No compiler, so unit testing is crucial<\/li>\n<li>No auto type conversion \u2026 \u201c3\u201d + 4 results in a TypeError<\/li>\n<li>Created in Japan in 1995 by Yukihiro Matsumoto \u201cMats\u201d\n<ul>\n<li>Inspired by Pearl and Smalltalk<\/li>\n<li>Popular after 2005<\/li>\n<\/ul>\n<\/li>\n<li>Run a file from irb \u2026 <span class=\"code\">load &#8216;.\/hello.rb&#8217;<\/span><\/li>\n<li>IRB = console = Interactive Ruby (you can hookup to your actual app and do stuff to it)<\/li>\n<li>The second line is just IRB\u2019s way of telling us the result of the last expression it evaluated<\/li>\n<li>\n<pre style=\"box-sizing: border-box; word-wrap: break-word; overflow-wrap: break-word; box-shadow: rgba(0, 0, 0, 0.4) 0px 0px 4px inset; text-shadow: #ffffff 0px 1px 0px; padding: 12px 16px; border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;\"><code class=\"irb\" style=\"box-sizing: border-box; word-wrap: break-word; overflow-wrap: break-word; margin: 0px; padding: 0px; border: none; text-shadow: #ffffff 0px 1px 0px; border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; white-space: normal; -webkit-text-size-adjust: auto; background-color: rgba(255, 255, 255, 0);\"><span style=\"font-family: OpenSans, sans-serif;\"><span class=\"k\" style=\"box-sizing: border-box; font-weight: bold;\">def<\/span> <span class=\"nf\" style=\"box-sizing: border-box; font-weight: bold;\">h<\/span><span class=\"p\" style=\"box-sizing: border-box;\">(<\/span><span class=\"nb\" style=\"box-sizing: border-box;\">name<\/span> <span class=\"o\" style=\"box-sizing: border-box; font-weight: bold;\">=<\/span> <span class=\"s2\" style=\"box-sizing: border-box;\">\"World\"<\/span><span class=\"p\" style=\"box-sizing: border-box;\">) is how you declare a default value if none is passed to the method<\/span><\/span><\/code><\/pre>\n<\/li>\n<li>#{name} or #{@name} is how you insert the value of a variable into a string<\/li>\n<li>@blahblah is an instance variable and available to all the methods of the class<\/li>\n<li>Create an object to set a class in motion<\/li>\n<li>CLASSNAME.instance_methods to list ALL methods including ancestor methods, or CLASSNAME.instance_methods(false) to exclude ancestor methods<\/li>\n<li>Test if your object responds to a method &#8230; OBJECTINSTANCENAME.respond_to?(&#8220;METHODNAME&#8221;)<\/li>\n<li>Comments are written as <span class=\"code\"># comment<\/span><\/li>\n<li><span class=\"code\">=begin =end<\/span> (multi-line comment)<\/li>\n<li><span style=\"-webkit-text-size-adjust: auto; background-color: rgba(255, 255, 255, 0);\">In Ruby, anything on a line after a hash mark is a comment and is ignored by the interpreter. The first line of the file is a special case, and under a Unix-like operating system tells the shell how to run the file<\/span><\/li>\n<li><span style=\"-webkit-text-size-adjust: auto; background-color: rgba(255, 255, 255, 0);\">A block is like an anonymous function or\u00a0<code style=\"box-sizing: border-box; word-wrap: break-word; overflow-wrap: break-word; margin: 0px 2px; padding: 0px 5px; border: 1px solid #dddddd; text-shadow: #ffffff 0px 1px 0px; border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;\">lambda<\/code>. The variable between pipe characters is the parameter for this block.<\/span><\/li>\n<li><span style=\"-webkit-text-size-adjust: auto; background-color: rgba(255, 255, 255, 0);\">The technique of not caring about the actual\u00a0<em style=\"box-sizing: border-box;\">type<\/em>\u00a0of a variable, just relying on what methods it supports is known as \u201cDuck Typing\u201d, as in \u201cif it walks like a duck and quacks like a duck\u2026\u201d. The benefit of this is that it doesn\u2019t unnecessarily restrict the types of variables that are supported. If someone comes up with a new kind of list class, as long as it implements the\u00a0<code style=\"box-sizing: border-box; word-wrap: break-word; overflow-wrap: break-word; margin: 0px 2px; padding: 0px 5px; border: 1px solid #dddddd; text-shadow: #ffffff 0px 1px 0px; border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;\">join<\/code>\u00a0method with the same semantics as other lists, everything will work as planned.<\/span><\/li>\n<li>\n<div class=\"highlight\" style=\"box-sizing: border-box;\">\n<pre style=\"box-sizing: border-box; word-wrap: break-word; overflow-wrap: break-word; box-shadow: rgba(0, 0, 0, 0.4) 0px 0px 4px inset; text-shadow: #ffffff 0px 1px 0px; padding: 12px 16px; border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;\"><code class=\"ruby\" style=\"box-sizing: border-box; word-wrap: break-word; overflow-wrap: break-word; margin: 0px; padding: 0px; border: none; text-shadow: #ffffff 0px 1px 0px; border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; white-space: normal; -webkit-text-size-adjust: auto; background-color: rgba(255, 255, 255, 0);\"><span style=\"font-family: OpenSans, sans-serif;\"><span class=\"k\" style=\"box-sizing: border-box; font-weight: bold;\">if<\/span> <span class=\"bp\" style=\"box-sizing: border-box;\">__FILE__<\/span> <span class=\"o\" style=\"box-sizing: border-box; font-weight: bold;\">==<\/span> <span class=\"vg\" style=\"box-sizing: border-box;\">$0<\/span>\r\n<\/span><\/code><\/pre>\n<\/div>\n<p style=\"box-sizing: border-box; margin: 20px 0px; text-rendering: optimizelegibility; word-wrap: break-word; overflow-wrap: break-word;\"><span style=\"font-family: OpenSans, sans-serif;\"><span style=\"line-height: normal; -webkit-text-size-adjust: auto; background-color: rgba(255, 255, 255, 0);\"><code style=\"box-sizing: border-box; word-wrap: break-word; overflow-wrap: break-word; margin: 0px 2px; padding: 0px 5px; border: 1px solid #dddddd; text-shadow: #ffffff 0px 1px 0px; border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;\">__FILE__<\/code>\u00a0is the magic variable that contains the name of the current file.\u00a0<code style=\"box-sizing: border-box; word-wrap: break-word; overflow-wrap: break-word; margin: 0px 2px; padding: 0px 5px; border: 1px solid #dddddd; text-shadow: #ffffff 0px 1px 0px; border-top-left-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;\">$0<\/code>\u00a0is the name of the file used to start the program. This check says \u201cIf this is the main file being used\u2026\u201d This allows a file to be used as a library, and not to execute code in that context, but if the file is being used as an executable, then execute that code.<\/span><\/span><\/p>\n<\/li>\n<li>Ruby is slower than Java<\/li>\n<li>Hash &#8230; <span class=\"code\">options = {1=&gt;\u2019a\u2019, \u2018foo\u2019=&gt;42}<\/span><\/li>\n<li><span class=\"code\">:sort<\/span> is a symbol<\/li>\n<li><span class=\"code\">nil<\/span> is an object of type NilClass (true or false)<\/li>\n<li>Range &#8230;\u00a0<span class=\"code\">score = 0..100<\/span> (two or three dots \u2026 one is inclusive and the other is not)<\/li>\n<li>You can swap variables without temp assignments<\/li>\n<li>Variables must start with lowercase or underscore<\/li>\n<li>if, if\/else, unless,\u00a0case-when-when-else-end<\/li>\n<li>case VARIABLE \u2026 when 20<\/li>\n<li>Ternary ? this : else<\/li>\n<li><span class=\"code\">=~<\/span> is a regex matcher<\/li>\n<li><span class=\"code\">&lt;=&gt;<\/span> is the spaceship operator \u2026 less than is -1, equals is 0, greater is 1<\/li>\n<li>Methods and blocks are used instead of while and for loops<\/li>\n<li>Snake Case = this_is_snake_case (use for variables)<\/li>\n<li>Camel Case = ThisIsCamelCase (use for class)<\/li>\n<li>Why is it Ruby <strong>on\u00a0Rails<\/strong>? &#8230; because Rails is a gem which is a library. Gems is the package thingy. (<a href=\"apidock.com\" target=\"_blank\">apidock.com<\/a>)<\/li>\n<li>An object is a combination of state (for example, the quantity and the product ID) and methods that use that state (perhaps a method to calculate the line item\u2019s total cost)<\/li>\n<li>Objects are created by calling a constructor, a special method associated with a class; the standard constructor is called new()<\/li>\n<li>Parentheses are generally optional in method calls<\/li>\n<li>Names in Ruby have special rules&#8230;\n<ul>\n<li>Local variables, method parameters, and method names should all start with a lowercase letter or with an underscore and be snake-case &#8230; like_this<\/li>\n<li>Instance variables begin with &#8216;@&#8217;<\/li>\n<li>Class names, module names, and constants must start with an uppercase letter<\/li>\n<li>Rails uses symbols to identify things (string literals magically made into constants) and they begin with a &#8216;:&#8217;\n<ul>\n<li>In particular, it uses them as keys when naming method parameters and looking things up in hashes such as &#8230; redirect_to :action =&gt; &#8220;edit&#8221;, :id =&gt; params[:id]<\/li>\n<li>Alternatively, you can <strong>consider the colon to mean &#8220;thing named,&#8221;<\/strong> so :id is &#8220;the thing named id.&#8221;<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<li>Ruby uses <span class=\"code\">end<\/span> instead of braces to delimit the bodies of compound statements and definitions (such as methods and classes)<\/li>\n<li>The keyword <span class=\"code\">return<\/span> is optional, and if not present, the results of the last expression evaluated will be returned<\/li>\n<li>String literals are sequences of characters between single or double quotation marks\n<ul>\n<li>Ruby does more work to process strings in double quotes\n<ul>\n<li>First, it substitutes sequences starting with a backslash (e.g. \\n is replaced with a newline character)\n<ul>\n<li>When you write a string containing a newline to the console, the \\n forces a line break<\/li>\n<\/ul>\n<\/li>\n<li>Second, Ruby performs expression interpolation &#8230;\u00a0<span class=\"code\">#{expression}<\/span><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<li>Array literals &#8230; <span class=\"code\">[1, &#8216;test&#8217;, 3.14]<\/span><\/li>\n<li><span class=\"code\">nil<\/span> is an object that represents nothing\n<ul>\n<li>The method <span class=\"code\">&lt;&lt;()<\/span> is commonly used with arrays to append a value<\/li>\n<\/ul>\n<\/li>\n<li>Ruby has a shortcut for creating an array of words&#8230;\n<ul>\n<li>a = %w{ ant bee cat dog elk } &#8230; === &#8230; a = [ &#8216;ant&#8217;, &#8216;bee&#8217;, &#8216;cat&#8217;, &#8216;dog&#8217;, &#8216;elk&#8217; ]<\/li>\n<\/ul>\n<\/li>\n<li>Hashes&#8230;\n<pre>inst_section = {\r\n  :drum =&gt; 'percussion',\r\n  :trumpet =&gt; 'brass',\r\n  :violin =&gt; 'string'\r\n}\r\n\r\ninst_section = {\r\n  drum: 'percussion',\r\n  trumpet: 'brass',\r\n  violin: 'string'\r\n}\r\n<\/pre>\n<\/li>\n<li>The following code fragment shows a two-element hash being passed to the redirect_to() method. In effect, though, you can ignore that it\u2019s a hash and pretend that Ruby has keyword arguments&#8230;\n<pre>redirect_to action: 'show', id: product.id<\/pre>\n<\/li>\n<li>In Ruby, you typically create a regular expression by writing <span class=\"code\">\/pattern\/<\/span> or <span class=\"code\">%r{pattern}<\/span><\/li>\n<li>Programs typically test strings against regular expressions using the<span class=\"code\"> =~<\/span> match operator\n<pre>if line =~ \/P(erl|ython)\/\r\n  puts \"There seems to be another scripting language here\"\r\nend\r\n<\/pre>\n<\/li>\n<li>Ruby control structures &#8230; if, while, unless, until\n<ul>\n<li>Ruby statement modifier shortcuts for single expressions&#8230; (e.g.\u00a0<span class=\"code\">puts &#8220;Danger, Will Robinson&#8221; if radiation &gt; 3000<\/span>)<\/li>\n<li>In Ruby, blocks and iterators are often used in place of looping constructs\n<ul>\n<li>Braces for single-line blocks and do\/end for multiline blocks<\/li>\n<li>You can pass a block to a method after any parameters\n<ul>\n<li>A method can invoke an associated block one or more times using the Ruby <span class=\"code\">yield<\/span> statement<\/li>\n<li>You can pass values to the block by giving parameters to <span class=\"code\">yield<\/span><\/li>\n<li>Within the block, you list the names of the arguments to receive these parameters between vertical bars (|)<\/li>\n<li>The &amp; prefix operator will allow a method to capture a passed block as a named parameter<\/li>\n<li>ARRAY<span class=\"code\">.each<\/span>, N<span class=\"code\">.times<\/span><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<li>Exceptions are objects of class <span class=\"code\">Exception<\/span> or its subclasses<\/li>\n<li>The <span class=\"code\">raise<\/span> method causes an exception to be raised<\/li>\n<li>Both methods and blocks of code wrapped between <span class=\"code\">begin<\/span> and <span class=\"code\">end<\/span> keywords intercept certain classes of exceptions using <span class=\"code\">rescue<\/span> clauses<\/li>\n<\/ul>\n<\/li>\n<li>There are two basic concepts in Ruby for organizing methods\u00a0&#8230;\u00a0<strong>classes and modules<\/strong>\n<ul>\n<li><span class=\"code\">class Order &lt; ActiveRecord::Base<\/span> &#8230;This Order class is defined to be a subclass of the class Base within the ActiveRecord module<\/li>\n<li>Methods making assertions about a class are called declarations (e.g.\u00a0<span class=\"code\">has_many :line_items<\/span>)<\/li>\n<li>Prefixing a method with <span class=\"code\">self<\/span> makes it a class method<\/li>\n<li>Objects of a class hold their state in instance variables\n<ul>\n<li>To make instance variables accessible outside of the class, write methods that return their values\n<pre>class Greeter\r\n  def initialize(name)\r\n    @name = name\r\n  end\r\n  def name\r\n    @name\r\n  end\r\n  def name=(new_name)\r\n    @name = new_name\r\n  end\r\nend\r\ng = Greeter.new(\"Barney\")\r\ng.name # =&gt; Barney\r\ng.name = \"Betty\"\r\ng.name # =&gt; Betty\r\n<\/pre>\n<ul>\n<li>Ruby provides convenience methods that write these accessor methods for you\n<pre>class Greeter\r\n  attr_accessor :name # create reader and writer methods\r\n  attr_reader :greeting # create reader only\r\n  attr_writer :age # create writer only\r\nend\r\n<\/pre>\n<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<li>The <span class=\"code\">private<\/span> directive is the strictest; private methods can be called only from within the same instance<\/li>\n<li><span class=\"code\">protected<\/span> methods can be called both in the same instance and by other instances of the same class and its subclasses<\/li>\n<li><strong>Modules<\/strong> can\u00a0hold a collection of methods, constants, and other module and class definitions\n<ul>\n<li>You cannot create objects based on modules<\/li>\n<li>Modules serve two purposes\n<ul>\n<li>Namespacing<\/li>\n<li>Sharing functionality between classes<\/li>\n<\/ul>\n<\/li>\n<li>Helper methods are an example of where Rails uses modules<\/li>\n<li>YAML (YAML Ain&#8217;t Markup Language) is a module in the standard Ruby library\u00a0used to define the configuration of things such as databases, test data, and translations<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n<li><strong>Marshaling<\/strong> &#8230; Ruby can take an object and convert it into a stream of bytes that can be stored outside the application<\/li>\n<li>Ruby method names can end with an exclamation mark (a bang method) or a question mark (a predicate method)\n<ul>\n<li>Bang methods normally do something destructive to the receiver<\/li>\n<li>Predicate methods return true or false depending on some condition<\/li>\n<\/ul>\n<\/li>\n<li><span class=\"code\">a || b<\/span> &#8230; a common way of returning a default value if the first value hasn&#8217;t been set<\/li>\n<li><span class=\"code\">count += 1<\/span> &#8230; assignment statements support shortcuts<\/li>\n<li><span class=\"code\">gets<\/span> method will prompt user for input\n<ul>\n<li>Adding the string <span class=\"code\">.chomp<\/span> method will remove carriage returns (\\n , \\r , and \\r\\n)<\/li>\n<\/ul>\n<\/li>\n<li><span class=\"code\">to_string<\/span> method turns a number into a string (helps when you want to concatenate it with text)<\/li>\n<\/ul>\n<h2>Resources<\/h2>\n<ul>\n<li>Agile Web Development with Rails 4 (course book)<\/li>\n<li><a href=\"http:\/\/rbenv.org\/\" target=\"_blank\">RBENV For Mac\/Linux<\/a><\/li>\n<li><a href=\"https:\/\/www.ruby-lang.org\/en\/documentation\/quickstart\/\" target=\"_blank\">Ruby in Twenty Minutes<\/a><\/li>\n<li><a href=\"http:\/\/www.ruby-doc.org\/\" target=\"_blank\">Ruby Documentation<\/a><\/li>\n<li><a href=\"http:\/\/apidock.com\/ruby\" target=\"_blank\">Better Documentation<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>ruby -v to check version Everything in Ruby is an object You don\u2019t declare variable types, but all objects have a type No compiler, so unit testing is crucial No auto type conversion \u2026 \u201c3\u201d + 4 results in a TypeError Created in Japan in 1995 by Yukihiro Matsumoto \u201cMats\u201d Inspired by Pearl and Smalltalk [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[144],"tags":[152],"class_list":["post-3670","post","type-post","status-publish","format-standard","hentry","category-web-shots","tag-ruby"],"_links":{"self":[{"href":"https:\/\/webninjataylor.com\/library\/wp-json\/wp\/v2\/posts\/3670","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/webninjataylor.com\/library\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/webninjataylor.com\/library\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/webninjataylor.com\/library\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/webninjataylor.com\/library\/wp-json\/wp\/v2\/comments?post=3670"}],"version-history":[{"count":54,"href":"https:\/\/webninjataylor.com\/library\/wp-json\/wp\/v2\/posts\/3670\/revisions"}],"predecessor-version":[{"id":3796,"href":"https:\/\/webninjataylor.com\/library\/wp-json\/wp\/v2\/posts\/3670\/revisions\/3796"}],"wp:attachment":[{"href":"https:\/\/webninjataylor.com\/library\/wp-json\/wp\/v2\/media?parent=3670"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/webninjataylor.com\/library\/wp-json\/wp\/v2\/categories?post=3670"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/webninjataylor.com\/library\/wp-json\/wp\/v2\/tags?post=3670"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}