Ruby: from zero to hero

  • View
    2.272

  • Download
    4

Embed Size (px)

Text of Ruby: from zero to hero

Ruby: from ZERO to HERODiego LEMOS@dlresende

BeginningCreated by Yukihiro Matsumoto, known as Matz, in the mid-1990s in Japan.

The Ruby LanguageRuby is a dynamic programming language with a complex but expressive grammar and a core class library with a rich and powerful API. Ruby draws inspiration from Lisp, Smalltalk, and Perl, but uses a grammar that is easy for C and Java programmers to learn. Ruby is a pure object-oriented language, but it is also suitable for procedural and functional programming styles. It includes powerful metaprogramming capabilities and can be used to create domain-specific languages or DSLs.

The Ruby PhilosophyRuby is designed to make programmers happy.

Is there a Ruby IDE?

Source: http://www.sitepoint.com/ides-rubyists-use/

Source: http://www.sitepoint.com/editor-rubyists-use/

Interpreter% ruby -e 'puts "hello world!"'hello world!

% ruby hello.rbhello world!

3 toolsirb

ri

gem

Interactive Ruby with irb$ irb>> "Ruby! " * 3=> "Ruby! Ruby! Ruby! ">> quit$

Ruby Documentation with riri Arrayri Array.sortri Hash#eachri Math::sqrt

Package Management with gem# gem install railsSuccessfully installed activesupport-1.4.4Successfully installed activerecord-1.15.5Successfully installed actionpack-1.13.5Successfully installed actionmailer-1.3.5Successfully installed actionwebservice-1.2.5Successfully installed rails-1.2.56 gems installedInstalling ri documentation for activesupport-1.4.4...Installing ri documentation for activerecord-1.15.5......etc...

Rake# Rake is a software task management and build automation # tool

task :default => [:test]

task :test do ruby "test/tc_simple_number.rb"end

app/ Bin/# Files for command-line execution lib/appname.rb# Classes and so onlolcatz/moar.rb# lolcatz::moar Rakefile# Tasks like testing, building Gemfile# Defines the source of the gem README test,spec,features/# Whichever means of testing you go for appname.gemspec# If it's a gem

Project Structure

Comments# Comment line with #

=beginComment multiple lines...like thisNot very popular=end

Arithmetic operators10 + 1 #=> 11 # addiction11 - 1 #=> 10 # subtraction10 * 2 #=> 20 # multiplication30 / 3 #=> 10 # division2 ** 5 #=> 32 # exponent17 % 3 #=> 2 # modulus

Comparison operators1 == 1 #=> true # equality8 != 1 #=> true # inequality10 < 2 #=> false # less than35 > 5 #=> true # greater than1 true # less than or equal to5 >= 5 #=> true # greater than or equal to

Combined comparison operator (1/2)1 10# => -110 1# => 11 1# => 0

Combined comparison operator (2/2)# === (case equality)

# For class Object, effectively the same as calling #==,# but typically overridden by descendants to provide meaningful# semantics in case statements.

case some_objectwhen /a regex/ # The regex matcheswhen 2..4 # some_object is in the range 2..4when lambda {|x| some_crazy_custom_predicate } # the lambda returned trueend

Regexp and Range# Regular Expressions and Ranges have a literal syntax in Ruby:

/[Rr]uby/ # Matches "Ruby" or "ruby"/\d{5}/ # Matches 5 consecutive digits1..3 # All x where 1 49 (0011 0001)# XOR~a # => -61 (1100 0011)# One Complementa 240 (1111 0000)# Left Shifta >> 2# => 15 (0000 1111)# Right Shift

Everything is Object# Numeric literals are objects3.class# => Fixnum3.to_s # => "3"

# Arithmetic is just syntactic sugar# for calling a method on an object1.+(3) # => 410.* 5 # => 50

Special Values are Objectsnil # equivalent to null in other languagestruefalse

nil.class# => NilClasstrue.class# => TrueClassfalse.class# => FalseClass

Logical Operators (1/2)!true #=> false# Nottrue && true #=> true # ANDtrue || false #=> true # ORnot true #=> false # Nottrue and true #=> true # Andtrue or 0 #=> true # Or

# and is the same as && but with lower precedence# they both use short-circuit evaluation (same for or)

Logical Operators (2/2)# and, or operators 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# Strings are objects

'I am a string'.class # => String "I am a string too".class # => String

# Prefer single quoted strings to double quoted ones where# possible# Double quoted strings perform additional inner calculations

String Interpolationplaceholder = 'use string interpolation'"I can #{placeholder} when using double quoted strings" # => "I can use string interpolation when using double quoted strings"

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"

# combine strings and operators 'hello ' * 3 # => "hello hello hello "

# append to string 'hello' "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

Assignments (1/3)x = 25 # => 25x # => 25

# Note that assignment returns the value assigned# This means you can do multiple assignment:

x = y = 10 # => 10x # => 10y # => 10

# By convention, use snake_case for variable namessnake_case = true

Assignments (2/3)# Assignment can be combined with operators such as + and - :

x += 1# Increment x: note Ruby does not have ++.y -= 1# Decrement y: no -- operator, either.

Assignments (3/3)# Ruby supports parallel assignment, allowing more than one value # and more than one variable in assignment expressions:

x, y = 1, 2 # Same as x = 1; y = 2a, b = b, a # Swap the value of two variablesx,y,z = [1,2,3] # Array elements automatically assigned to variables

Symbols# Symbols are objects.# Symbols are immutable, reusable constants represented# internally by an integer value. # They're often used instead of strings to efficiently convey# specific, meaningful values.

:pending.class # => Symbolstatus = :pendingstatus == :pending # => truestatus == 'pending' # => falsestatus == :approved # => false

Arrays (1/4)# This is an arrayarray = [1, 2, 3, 4, 5] # => [1, 2, 3, 4, 5]

# Arrays can contain items of different types[1, 'hello', false] # => [1, "hello", false]

Arrays (2/4)# Arrays can be indexed# ...from the frontarray[0] # => 1array.first # => 1array[12] # => nil

# ...from the endarray[-1] # => 5array.last # => 5

# ...with a start index and lengtharray[2, 3] # => [3, 4, 5]

# ...or with a rangearray[1..3] # => [2, 3, 4]

Arrays (3/4)

# Like arithmetic, [var] access# is just syntactic sugar# for calling a method [] on an objectarray.[](0) # => 1array.[] 0 # => 1array.[] 12 # => nil

# In Ruby, parentheses are usually optional and they are # commonly omitted, especially when the method being invoked # takes no arguments.

Arrays (4/4)# Reverse an Arraya = [1, 2, 3]a.reverse! # => [3, 2, 1]

# Add to an array like thisarray [1, 2, 3, 4, 5, 6]# Or like thisarray.push(6) # => [1, 2, 3, 4, 5, 6]

# Check if an item exists in the arrayarray.include?(1) # => true

Exclamation and question marksarray = [1, 2, 3]

# The question mark is a code style convention;# it indicates that a method returns a boolean value.# The question mark is a valid character at the end of a method.# These methods are called predicated methods.array.include?(1) # => true

# In general, methods that end in ! indicate that the method will# modify the object it's called on. Ruby calls these "dangerous# methods" because they change state that someone else might # have a reference to.# These methods are called mutator methods.array.reverse! # => [3, 2, 1]

array # => [3, 2, 1]

Hashes (1/2)# Hashes are Ruby's primary dictionary with keys/value pairs.# Hashes are denoted with curly braces:hash = { 'color' => 'green', 'number' => 5 }

hash.keys # => ['color', 'number']

# Hashes can be quickly looked up by key:hash['color'] # => 'green'hash['number'] # => 5

# Asking a hash for a key that doesn't exist returns nil:hash['nothing here'] # => nil

# Since Ruby 1.9, there's a special syntax when using symbols as# keys.# Hashes can use any object as a key, but Symbol objects are the # most commonly used. Symbols are immutable, interned strings.new_hash = { defcon: 3, action: true }

new_hash.keys # => [:defcon, :action]new_hash.values # => [3, true]

# Check the existence of keys and values in hashnew_hash.key?(:defcon) # => truenew_hash.value?(3) # => true

# Tip: Both Arrays and Hashes are Enumerable# They share a lot of useful methods such as each, map, count,# and moreHashes (2/2)

# Code blocks are chunks of code that you can associate with# method invocations. Its analogous to lambdas, # anonymous functions or closures in other languages.

# We can define blocks between braces...some_method { puts 'hello' }

# ...or between do..endsome_method do print 'hello ' print 'world'end

# The Ruby standard is to use braces {} for single-line blocks and # do..end for multi-line blocks.Blocks (1/2)

# The keyword yield executes the block passed to the methoddef some_me