за Ruby
-
Upload
stefan-kanev -
Category
Technology
-
view
660 -
download
8
description
Transcript of за Ruby
♥?
&&
ЗЛО! АНАТЕМА!
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420198938095257201065485863278865936153381827968230301952035301852968995773622599413891249721775283479131515574857242454150695950829533116861727855889075098381754637464939319255060400927701671139009848824012858361603563707660104710181942955596198946767837449448255379774726847104047534646208046684259069491293313677028989152104752162056966024058038150193511253382430035587640247496473263914199272604269922796782354781636009341721641219924586315030286182974555706749838505494588586926995690927210797509302955
instance Show Board where show (Board ps) = let ordered = (sort . swap) ps ranks = map (showRank ordered) [8,7..1] board = intersperse "--+--+--+--+--+--+--+--" ranks rlabels = intersperse " " (map (\n->(show n)++" ") [8,7..1]) flabels = " a b c d e f g h" in unlines $ zipWith (++) rlabels board ++ [flabels] where swap = map (\(a,b)->(b,a)) showRank ps r = let rnk = filter (\(p,_)->(rank p)==r) ps cs = map (showPiece rnk) [A .. H] in concat (intersperse "|" cs) showPiece ps f = maybe " " (show . snd) (find (\(p,_)->(file p)==f) ps)
ЗаСтефан Кънев -- 28 май -- initLab
Защо?
&&
• Налага се да работиш извънработно време. Като проститутка.
• Налага се да работиш извънработно време. Като проститутка.
• Обикновенно работиш до късно. Като проститутка.
• Налага се да работиш извънработно време. Като проститутка.
• Обикновенно работиш до късно. Като проститутка.
• Никога няма да започнеш да се гордееш с работата си. Като проститутка.
• Налага се да работиш извънработно време. Като проститутка.
• Обикновенно работиш до късно. Като проститутка.
• Никога няма да започнеш да се гордееш с работата си. Като проститутка.
• Когато те питат с какво се занимаваш - не можеш да обясниш. Като проститутка.
• Налага се да работиш извънработно време. Като проститутка.
• Обикновенно работиш до късно. Като проститутка.
• Никога няма да започнеш да се гордееш с работата си. Като проститутка.
• Когато те питат с какво се занимаваш - не можеш да обясниш. Като проститутка.
• В края края на крайщата се чувстваш сякаш си се измъкнал от ада. Като проститутка.
• Налага се да работиш извънработно време. Като проститутка.
• Обикновенно работиш до късно. Като проститутка.
• Никога няма да започнеш да се гордееш с работата си. Като проститутка.
• Когато те питат с какво се занимаваш - не можеш да обясниш. Като проститутка.
• В края края на крайщата се чувстваш сякаш си се измъкнал от ада. Като проститутка.
• Ако нещо не е както трябва, виновният си ти. Като проститутка.
• Налага се да работиш извънработно време. Като проститутка.
• Обикновенно работиш до късно. Като проститутка.
• Никога няма да започнеш да се гордееш с работата си. Като проститутка.
• Когато те питат с какво се занимаваш - не можеш да обясниш. Като проститутка.
• В края края на крайщата се чувстваш сякаш си се измъкнал от ада. Като проститутка.
• Ако нещо не е както трябва, виновният си ти. Като проститутка.
• И се питаш накрая: "АБЕ, аз системен администратор ли съм или ....?"
s/сис админ/програмист/
Занаят
ЗанаятПредизвикателство
ЗанаятПредизвикателство
Изкуство
Fun
C#AspectJGroovyPerl
Python
Ruby
class < ProgrammingLanguage
class < ProgrammingLanguage is_not :rails
class < ProgrammingLanguage is_not :rails is :general_purpose
class < ProgrammingLanguage is_not :rails is :general_purpose is :dynamic
class < ProgrammingLanguage is_not :rails is :general_purpose is :dynamic kicks_ass
class < ProgrammingLanguage is_not :rails is :general_purpose is :dynamic kicks_assend
duck typing
динамичен
обектно-ориентиран
интерпретира се
general purpose
ала Perl и Python
вдъхновен от Perl, Smalltalk, CLU и Lisp
+
ООП
regarding(:oop) { "Ruby" > "Python"}
print reverse "dog";
print reverse "dog";> dog
print reverse "dog";> dog
print ucfirst reverse "dog";
print reverse "dog";> dog
print ucfirst reverse "dog";> God
regarding(:readability) { "Ruby" > "Perl"}
Динамичен
≠
Идеология
Matz
Treating Code As an Essay
•Brevity
•Simplicity
•Balance
Programs must bewritten for people
to read,and only incidentally
for machines toexecute
Ruby.syntax
# Променливи и константиsavings = 1729savings = savings - 42PI = 3.1415
# Условни конструкцииif price < 100 savings -= price will_buy = yeselse will_buy = noend
# Циклиwhile savings > 1000 product, cost = find_cool_stuff() buy(product) savings -= costend
# Unless и Untilunless hungry continue_programming()end
until broke buy_stuff()end
# Като модификаториbuy(product) if price < 100continue_programming() unless hungrybuy_another() while savings > 1000buy_stuff() until broke
# Вградени типовеprimes = [2, 3, 5, 7, 11, 13]names = ["Matz", "DHH", "_why"]family_names = { "Yukihiro" => "Matsumoto", "David" => "Heinemeier Hanson", "_why" => "the lucky stiff",}regex = /(bb|[^b]{2})/
# Итерацияprimes = [2, 3, 5, 7, 11, 13]for n in primes puts nend
primes.each do |n| puts nend
# Функцииdef factorial(n) if n <= 1 return 1 else return n * factorial(n - 1) endend
factorial(5)
# Функции (2)def double(n) n + nend
double(5) == 10
# Всичко е изразclassification = if price > 1000 "Expensive" elsif price > 300 "Normal" else "Cheap" end
# Функции (3)def factorial(n) if n <= 1 1 else n * factorial(n - 1) endend
# Функционално програмиранеactive_emails = []for user in users if user.active? active_emails << user.email endend
# Функционално програмиране (2)active_users = users.select { |user| user.active? }active_emails = active_users.map { |user| user.email }
# Функционално програмиране (3)active_users = users.select { |user| user.active? }active_emails = active_users.map { |user| user.email }
active_emails = users.select { |u| u.active? }.map { |u| u.email }active_emails = users.select(&:active?).map(&:email)
# Обектно-ориентирано програмиранеa = Vector.new(0, 1, 0)b = Vector.new(1, 0, 1)product = a * blen = (a.x*a.x + a.y*a.y + a.z*a.z) ** 0.5
# Обектно-ориентирано програмиране (2)class Vector def initialize(x, y, z) @x = x @y = y @z = z end def len (@x * @x + @y * @y + @z * @z) ** 0.5 end def *(other) ... endend
# Обектно-ориентирано програмиране (3)class Vector def x() @x end def x=(val) @x = val endend
a = Vector(0, 1, 0)puts a.xputs a.x()a.x = 10a.x=(10)
# Обектно-ориентирано програмиране (4)class Vector attr_accessor :x attr_accessor :yend
# Корутиниwrite_to = users.select { |u| u.active? }.map { |u| u.email }
primes = [1, 2, 3, 5, 7, 11, 13]sum = primes.inject { |a, b| a + b }
open("foo.txt", "w") do |file| primes.each do |prime| file.write prime.to_s endend
# Корутини (2)def do_twice yield yieldend
do_twice { puts "Ruby rocks!" }
# Корутини (3)def filter(things) result = [] things.each do |thing| result << thing if yield(thing) end resultend
filter([3, 5, 7, 11, 13, 17]) { |x| x > 10 }
# Всички прости числа до 1002.upto(100) do |n| puts n if (2...n).all? { |x| n % x != 0 }end
# Mix-inmodule FunctionalStuff def map result = [] self.each { |item| result << yield(item) } result end def select result = [] self.each { |item| result << item if yield(item) } result endend
class PrimesUpTo include FunctionalStuff def each ... endend
# Monkey patchclass Integer def factorial() (1..self).inject { |a, b| a * b } endend
puts 5.factorial
arr = [ "Freddie", "Herbie", "Ron", "Max", "Ringo" ]callcc{|$cc|}puts(message = arr.shift)$cc.call unless message =~ /Max/
# Freddie# Herbie# Ron# Max
callcc {|cont| for i in 0..4 print "\n#{i}: " for j in i*5...(i+1)*5 cont.call() if j == 17 printf "%3d", j end end}print "\n"
#0: 0 1 2 3 4#1: 5 6 7 8 9#2: 10 11 12 13 14#3: 15 16
(->_{_%_})['(->_{%%}_)[%p]']
На практика
DomainSpecificLanguages
RSpecdescribe Stack do before(:each) do @stack = Stack.new [1, 2, 3, 4].each { |n| @stack << n } end it "should have all items in reversed order" do @stack.should_not be_empty @stack.should have(4).items @stack.items.should == [4, 3, 2, 1] end it "should be empty if emptied" do 4.times { @stack.pop } @stack.should be_empty @stack.should have(:no).items endend
ShoesShoes.app do background "#eee" @list = stack do para "Enter a URL to download:", :margin => [10, 8, 10, 0] flow :margin => 10 do @url = edit_line :width => -120 button "Download", :width => 120 do @list.append do stack do background "#eee".."#ccd" stack :margin => 10 do dl = nil para @url.text, " [", link("cancel") { dl.abort }, "]", :margin => 0 d = inscription "Beginning transfer.", :margin => 0 p = progress :width => 1.0, :height => 14 dl = download @url.text, :save => File.basename(@url.text), :progress => proc { |dl| d.text = "Transferred #{dl.transferred} of #{dl.length} b (#{dl.percent}%)" p.fraction = dl.percent * 0.01 }, :finish => proc { |dl| d.text = "Download completed" } end end end end end endend
ActiveRecordclass User < ActiveRecord::Base
validates_presence_of :name, :faculty_number, :email validates_presence_of :password, :if => :password_required? validates_presence_of :password_confirmation, :if => :password_required? validates_length_of :password, :within => 4..40, :if => :password_required? validates_confirmation_of :password, :if => :password_required? validates_length_of :email, :within => 3..100 validates_uniqueness_of :email, :case_sensitive => false before_save :encrypt_password
file_column :picture, :magick => { :geometry => "100x100>" }
has_many :solutions has_many :topics has_many :replies belongs_to :project
end
Culture
≈
Innovation
ИноваториПсихопати
Anti-professionalismUn-professionalism
Elitism
Леко аматьорска(само мъничко)
Interpreters:MRIYARVJRuby
Rubinius
Resources