diff options
Diffstat (limited to 'ruby.html.markdown')
| -rw-r--r-- | ruby.html.markdown | 201 | 
1 files changed, 145 insertions, 56 deletions
| diff --git a/ruby.html.markdown b/ruby.html.markdown index 962853a2..3eed2d3c 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -9,7 +9,12 @@ contributors:    - ["Nick LaMuro", "https://github.com/NickLaMuro"]    - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]    - ["Ariel Krakowski", "http://www.learneroo.com"] - +  - ["Dzianis Dashkevich", "https://github.com/dskecse"] +  - ["Levi Bostian", "https://github.com/levibostian"] +  - ["Rahil Momin", "https://github.com/iamrahil"] +  - ["Gabriel Halley", "https://github.com/ghalley"] +  - ["Persa Zula", "http://persazula.com"] +  - ["Jake Faris", "https://github.com/farisj"]  ---  ```ruby @@ -35,7 +40,13 @@ You shouldn't either  8 - 1 #=> 7  10 * 2 #=> 20  35 / 5 #=> 7 -2 ** 5 #=> 32 +2**5 #=> 32 +5 % 3 #=> 2 + +# Bitwise operators +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6  # Arithmetic is just syntactic sugar  # for calling a method on an object @@ -43,7 +54,7 @@ You shouldn't either  10.* 5 #=> 50  # Special values are objects -nil # Nothing to see here +nil # equivalent to null in other languages  true # truth  false # falsehood @@ -58,8 +69,6 @@ false.class #=> FalseClass  # Inequality  1 != 1 #=> false  2 != 1 #=> true -!true  #=> false -!false #=> true  # apart from false itself, nil is the only other 'falsey' value @@ -73,22 +82,57 @@ false.class #=> FalseClass  2 <= 2 #=> true  2 >= 2 #=> true +# Combined comparison operator +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + +# Logical operators +true && false #=> false +true || false #=> true +!true #=> false + +# There are alternate versions of the logical operators with much lower +# precedence. These are meant to be used as flow-control constructs to chain +# statements together until one of them returns true or false. + +# `do_something_else` only called if `do_something` succeeds. +do_something() and do_something_else() +# `log_error` only called if `do_something` fails. +do_something() or log_error() + +  # Strings are objects  'I am a string'.class #=> String  "I am a string too".class #=> String -placeholder = "use string interpolation" +placeholder = 'use string interpolation'  "I can #{placeholder} when using double quoted strings"  #=> "I can use string interpolation when using double quoted strings" +# Prefer single quoted strings to double quoted ones where possible +# Double quoted strings perform additional inner calculations +  # Combine strings, but not with numbers -"hello " + "world"  #=> "hello world" -"hello " + 3 #=> TypeError: can't convert Fixnum into String -"hello " + 3.to_s #=> "hello 3" +'hello ' + 'world'  #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# Combine strings and operators +'hello ' * 3 #=> "hello hello hello " + +# Append to string +'hello' << ' world' #=> "hello world" -# print to the output +# print to the output with a newline at the end  puts "I'm printing!" +#=> I'm printing! +#=> nil + +# print to the output without a newline +print "I'm printing!" +#=> I'm printing! => nil  # Variables  x = 25 #=> 25 @@ -130,11 +174,12 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]  # Arrays can contain different types of items -[1, "hello", false] #=> [1, "hello", false] +[1, 'hello', false] #=> [1, "hello", false]  # Arrays can be indexed  # From the front  array[0] #=> 1 +array.first #=> 1  array[12] #=> nil  # Like arithmetic, [var] access @@ -145,19 +190,29 @@ array.[] 12 #=> nil  # From the end  array[-1] #=> 5 +array.last #=> 5  # With a start index and length  array[2, 3] #=> [3, 4, 5] +# Reverse an Array +a=[1,2,3] +a.reverse! #=> [3,2,1] +  # Or with a range  array[1..3] #=> [2, 3, 4]  # Add to an array like this  array << 6 #=> [1, 2, 3, 4, 5, 6] +# Or like this +array.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Check if an item exists in an array +array.include?(1) #=> true  # Hashes are Ruby's primary dictionary with keys/value pairs.  # Hashes are denoted with curly braces: -hash = {'color' => 'green', 'number' => 5} +hash = { 'color' => 'green', 'number' => 5 }  hash.keys #=> ['color', 'number'] @@ -170,21 +225,25 @@ hash['nothing here'] #=> nil  # Since Ruby 1.9, there's a special syntax when using symbols as keys: -new_hash = { defcon: 3, action: true} +new_hash = { defcon: 3, action: true }  new_hash.keys #=> [:defcon, :action] +# Check existence of keys and values in hash +new_hash.key?(:defcon) #=> true +new_hash.value?(3) #=> true +  # Tip: Both Arrays and Hashes are Enumerable  # They share a lot of useful methods such as each, map, count, and more  # Control structures  if true -  "if statement" +  'if statement'  elsif false -  "else if, optional" +  'else if, optional'  else -  "else, also optional" +  'else, also optional'  end  for counter in 1..5 @@ -216,7 +275,7 @@ end  #=> iteration 5  # You can also surround blocks in curly brackets: -(1..5).each {|counter| puts "iteration #{counter}"} +(1..5).each { |counter| puts "iteration #{counter}" }  # The contents of data structures can also be iterated using each.  array.each do |element| @@ -226,6 +285,12 @@ hash.each do |key, value|    puts "#{key} is #{value}"  end +# If you still need and index you can use "each_with_index" and define an index +# variable +array.each_with_index do |element, index| +  puts "#{element} is number #{index} in the array" +end +  counter = 1  while counter <= 5 do    puts "iteration #{counter}" @@ -237,38 +302,62 @@ end  #=> iteration 4  #=> iteration 5 +# There are a bunch of other helpful looping functions in Ruby, +# for example "map", "reduce", "inject", the list goes on. Map, +# for instance, takes the array it's looping over, does something +# to it as defined in your block, and returns an entirely new array. +array = [1,2,3,4,5] +doubled = array.map do |element| +  element * 2 +end +puts doubled +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] +  grade = 'B'  case grade  when 'A' -  puts "Way to go kiddo" +  puts 'Way to go kiddo'  when 'B' -  puts "Better luck next time" +  puts 'Better luck next time'  when 'C' -  puts "You can do better" +  puts 'You can do better'  when 'D' -  puts "Scraping through" +  puts 'Scraping through'  when 'F' -  puts "You failed!" +  puts 'You failed!'  else -  puts "Alternative grading system, eh?" +  puts 'Alternative grading system, eh?'  end -  #=> "Better luck next time"  # cases can also use ranges  grade = 82  case grade -    when 90..100 -      puts "Hooray!" -    when 80...90 -      puts "OK job"  -    else -      puts "You failed!" +when 90..100 +  puts 'Hooray!' +when 80...90 +  puts 'OK job' +else +  puts 'You failed!'  end -  #=> "OK job" +# exception handling: +begin +  # code here that might raise an exception +  raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable +  puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable +  puts 'RuntimeError was raised now' +else +  puts 'This runs if no exceptions were thrown at all' +ensure +  puts 'This code always runs no matter what' +end  # Functions @@ -284,23 +373,23 @@ double 3 #=> 6  double double 3 #=> 12 -def sum(x,y) +def sum(x, y)    x + y  end  # Method arguments are separated by a comma  sum 3, 4 #=> 7 -sum sum(3,4), 5 #=> 12 +sum sum(3, 4), 5 #=> 12  # yield  # All methods have an implicit, optional block parameter  # it can be called with the 'yield' keyword  def surround -  puts "{" +  puts '{'    yield -  puts "}" +  puts '}'  end  surround { puts 'hello world' } @@ -311,25 +400,25 @@ surround { puts 'hello world' }  # You can pass a block to a function -# "&" marks a reference to a passed block  +# "&" marks a reference to a passed block  def guests(&block) - block.call "some_argument"  +  block.call 'some_argument'  end -  +  # You can pass a list of arguments, which will be converted into an array -# That's what splat operator ("*") is for  +# That's what splat operator ("*") is for  def guests(*array) - array.each { |guest| puts "#{guest}" } +  array.each { |guest| puts guest }  end  # Define a class with the class keyword  class Human    # A class variable. It is shared by all instances of this class. -  @@species = "H. sapiens" +  @@species = 'H. sapiens'    # Basic initializer -  def initialize(name, age=0) +  def initialize(name, age = 0)      # Assign the argument to the "name" instance variable for the instance      @name = name      # If no age given, we will fall back to the default in the arguments list. @@ -356,20 +445,19 @@ class Human    # A class method uses self to distinguish from instance methods.    # It can only be called on the class, not an instance.    def self.say(msg) -    puts "#{msg}" +    puts msg    end    def species      @@species    end -  end  # Instantiate a class -jim = Human.new("Jim Halpert") +jim = Human.new('Jim Halpert') -dwight = Human.new("Dwight K. Schrute") +dwight = Human.new('Dwight K. Schrute')  # Let's call a couple of methods  jim.species #=> "H. sapiens" @@ -380,7 +468,7 @@ dwight.species #=> "H. sapiens"  dwight.name #=> "Dwight K. Schrute"  # Call the class method -Human.say("Hi") #=> "Hi" +Human.say('Hi') #=> "Hi"  # Variable's scopes are defined by the way we name them.  # Variables that start with $ have global scope @@ -399,7 +487,7 @@ defined? @@var #=> "class variable"  Var = "I'm a constant"  defined? Var #=> "constant" -# Class also is object in ruby. So class can have instance variables. +# Class is also an object in ruby. So class can have instance variables.  # Class variable is shared among the class and all of its descendants.  # base class @@ -415,7 +503,7 @@ class Human    end  end -#  derived class +# derived class  class Worker < Human  end @@ -451,8 +539,8 @@ module ModuleExample    end  end -# Including modules binds the methods to the object instance -# Extending modules binds the methods to the class instance +# Including modules binds their methods to the class instances +# Extending modules binds their methods to the class itself  class Person    include ModuleExample @@ -467,7 +555,7 @@ Person.new.foo # => 'foo'  Book.foo       # => 'foo'  Book.new.foo   # => NoMethodError: undefined method `foo' -# Callbacks when including and extending a module are executed +# Callbacks are executed when including and extending a module  module ConcernExample    def self.included(base) @@ -500,9 +588,10 @@ Something.new.qux # => 'qux'  ## Additional resources -- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.  +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Learn Ruby through a series of interactive tutorials.  - [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)  - [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) -- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free addition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.  - - +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. +- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser. | 
