Upload
laszlo-bacsi
View
2.028
Download
0
Embed Size (px)
DESCRIPTION
This is an introduction into the Ruby programming language. The presentation took place in Virgo as a crash course into Ruby.
Citation preview
Ruby Crash CourseBácsi László, Virgo Systems
Mi az a Ruby?
Open Source programnyelv
Egy japán csávó csinálja 1993 óta
Objektum orientált
Dinamikus
Gyengén típusos
Objektum orientált
Minden objektum
Nincs többszörös öröklés, helyette Mix-in
Singleton objektumok
Metaprogramozás
Sajátosságok
Beszédes metódusnevek (sort!, exists?)
Könnyen olvasvató szintaxis
Iterátorok ciklusok helyett
Blokkok
Dinamikus
Duck Typing aka Dynamic Typing
Dynamic Dispatch
Dinamikus viselkedés
Reflekció
scope újranyitás, nyílt osztályok
eval
# Mi az `o' objektum osztálya?o = Hash.newo.class # => Hash
# Egy tömb hosszát a `size', vagy `length' metódus adja vissza?array = ['alice', 'bob', 'carol']array.length == array.size # => true# ugyanaz a metódus, össze vannak linkelve
# Mi két tömb különbsége?a2 = ['bob', 'charlie']difference = array - a2 # => ["alice", "carol"]union = array + a2 # => ["alice", "bob", "carol", "bob", "charlie"]real_union = array | a2 # => ["alice", "bob", "carol", "charlie"]
# Hogy hívhatók meg az ismert C függvények?Time.now.strftime('%Y-%m-%d %H:%M') # => "2008-08-12 15:02"
POLSPrinciple of Least Surprise
Kicsit részleteseben
5.times { print "Odelay!" }
Ismerkedés
['toast', 'cheese', 'wine'].each { |food| print food.capitalize }
exit unless "restaurant".include? "aura"
Ismerkedés# számok1, 42, -10000, 3.14, -273.15, 12.043e-04population = 10_041_000
# stringek"negyvenkettő", 'piros', %{akármi}"nem gondha több soros"<<ENDÉs van mégHEREDOCis.END
# szimbólumok (könnyű stringek):a, :b, :white_board
Ismerkedés
# konstansok nagybetűvel kezdődnekRAILS_ENV, Time, Array
# lokális változókx, y, banana, kicsi_piros
# globális változók$x, $!, $&, $LOAD_PATH, $stderr
# példány változók@a, @b, @first_name
# osztály változók@@master_password, @@site
# metódushívás ponttal, vagy osztályon `::'-al is lehet# elhagyható a zárójelpopulation.to_sTime::now
# ? és ! lehet a metódusnév végén0.zero?array.sort!
# lehet láncolnifront_door.paint(3, :red).dry(30).close
Ismerkedés
# blockok5.times { puts "Hello World!" }File.open("readme", "w") do |f| f << "Egy csomó hasznos infó"end[1,3,42,55].sort_by { |x| x % 10 }
# intervallumok(1..100), ('a'..'z'), (0...5)
Ismerkedés
# hashek{:modell => 'Audi A8', :szin => :fekete}{'one' => 'egy', 'two' => 'kettő'}
# tömbök[1, 2, 3], ['egy', 'ketto', 'harom'], %w{egy ketto harom}
# reguláris kifejezések/ruby/, /\d+/, /^[\w-]+$/, %r{\.jpg$}
# operátorok** ! ~ * / % + - &<< >> | ^ > >= < <= <=>|| != =~ !~ && += -= == ===.. ... not and or
Ismerkedés
# kulcsszavakalias and BEGIN begin break case class def defineddo else elsif END end ensure false for ifin module next nil not or redo rescue retryreturn self super then true undef unless until whenwhile yield
plastic_cup = nilplastic_cup.nil? # => trueglass_cup # ~> -:1: undefined local variable or method `glass_cup' for main:Object (NameError)
Nil
if plastic_cup print "Plastic cup is on the up 'n' up!" end
unless plastic_cup print "Plastic cup is on the down low." end
print "Yeah, plastic cup is up again!" if plastic_cupprint "Hardly. It's down." unless plastic_cup
print "We're using plastic 'cause we don't have glass." if plastic_cup unless glass_cup
kitty_toys = [ {:shape => 'sock', :fabric => 'cashmere'}, {:shape => 'mouse', :fabric => 'calico'}, {:shape => 'eggroll', :fabric => 'chenille'}]
next, break
kitty_toys.each do |toy| break if toy[:fabric] == 'chenille' p toyend
non_eggroll = 0kitty_toys.each do |toy| next if toy[:shape] == 'eggroll' non_eggroll = non_eggroll + 1end
at_work = trueemail = if at_work "[email protected]" else "[email protected]" end
Kiértékeléś
def timeline(year) case year when 1983 "Megszülettem" when 1984..1990 "Felhőtlen gyermekkor" when 1990..1996 "Általános iskola Budaörsön" when 1996..2002 "Illyés Gyula Gimnázium szorgos diákja" when 2002..2007 "Vegyesen BME és munka" when 2008..Time.now.year "Virgo" endend
Példák
require 'rubygems'require 'faker'class Person attr_accessor :first_name, :last_name def initialize first, last @first_name, @last_name = first, last end def <=> other last_name <=> other.last_name end def to_s "#{first_name} #{last_name}" end include Comparableendpersons = (1..10).map {Person.new(Faker::Name.first_name, Faker::Name.last_name)}puts persons.sort.map {|p| p.to_s}.join("\n")# prints## Trudie Cremin# Joshua Glover# Abdul Haley# Mortimer Harris# German Hartmann# Aleen Herzog# Adriel Kling# Zack Mann# Dorris McDermott# Cary Satterfield
Mix-in
Array.class # => ClassArray.new
Minden objektum
0.zero? # => true1.zero? # => false1.abs # => 1-1.abs # => 11.methods # => ["%", "inspect", "<<", etc... "[]", "is_a?"]2.+(3) # => 510.class # => Fixnum(10**100).class # => Bignum
a = nila.nil? # => truea.methods # => list of methodsa.abs # => NoMethodError
kivéve változó nevek és blokkok
Majdnem minden üzenet
értékadás és vezér szerkezeteken (if/else, while, etc.) kívül minden
nem metódus hívás, hanem üzenetküldés az objektumnak
string.index("x")# Send :index (with argument "x")string.length# Send :length (with no argument) run_status_reports# Send :run_status_reports (to self) 1 + 2# Send :+ (with argument 2) to the object 1 array[i]# Send :[] (with argument i) to the array
class VCR def initialize @messages = [] end def method_missing(method, *args, &block) @messages << [method, args, block] end def play_back_to(obj) @messages.each do |method, args, block| obj.send(method, *args, &block) end endend
Mi a különbség?
require 'src/vcr'
vcr = VCR.newvcr.sub!(/Java/) { "Ruby" }vcr.upcase!vcr[11,5] = "Universe"vcr << "!"
string = "Hello Java World"puts string
vcr.play_back_to(string)puts string
# OutputHello Java WorldHELLO RUBY Universe!
Referenciák
http://ruby-lang.org/
http://ruby-doc.org/
http://poignantguide.net/ruby/
felhasznált prezentációk
http://www.ruby-doc.org/whyruby/