Upload
stefan-kanev
View
2.622
Download
7
Embed Size (px)
Citation preview
Въведение в Ruby
Lecturers = [“Стефан Кънев”,“Николай Бачийски”]
Lecturers.each do |person|person.say_something_about :ruby
end
NAMES HAVE POWER
Имена
Неща
42
Числа
3.14
‘Chunky bacon’
Текст
“What’s up?”
answer = 42pi = 3.14food = “Chunky bacon”greeting = “What’s up?”
Имена != Неща
>> word = “oat”>> breakfast = word>> dinner = word>> word.insert(‘g’, 0)>> puts breakfastgoat
Действия
001:0> “shut up!”.upcase()=> “SHUT UP!”002:0> “wonderful”.sub(“wonde", “colo")=> “colorful”003:0> 3.14.floor=> 3004:0> 24.gcd 56=> 8005:0> “wonderful”.sub “wonde", “colo"=> “colorful”
001:0> puts “Tell me about bacon:”Tell me about bacon:002:0> input = gets
003:0> puts “You said: “, inputYou said:Chunky!
>> word = “oat”>> breakfast = word>> dinner = word>> word.insert(‘g’, 0)>> puts breakfastgoat
metaphor = {:име => :променлива,:нещо => :обект,:десйтвие => :метод
}
>> favorite = “Chunky bacon”>> Tax, Change = ‘20%’, ‘None’>> $important = “Money”
още: @name, @@members
Променливи
alias and BEGIN begin breakcase class def defined doelse elsif END end ensurefalse for if in modulenext nil not or redorescue retry return self superthen true undef unless untilwhen while yield
Вече заети
Неща
Цели числа42 ; ‐271 ; 1_024
Низове“bacon” ; ‘food’
С плаваща запетая3.1415 ; 2.71
Булеви данниtrue ; false
Масиви[2, 3, 5, 7, 11]
Хешове{‘one’ => 1, ‘two’ => 2}
Регулярни изрази/(bb)|([^b]{2})/
Области2..6 ; ‘a’...’z’
Символи:name ; :send ; :diff
Ламбдиlambda { |x| x ** 2 }‐> x { x ** 2}
ОбектиPerson.new
01729‐2711_000_0000377 # Осмични0b1001_0110 # Двоични0xDEADBEEF # Шестнадесетични
Числа
0.03.14‐273.151.22e281_000.001
… с плаваща запетая
Аритметика>> 2 + 2 ‐ 1=> 3>> 6 * 9=> 42 :)>> 14 / 4=> 3>> 14.0 / 4=> 3.5
>> 369 % 10=> 9>> (‐2) ** 8=> 256>> 2 ** 0.5=> 1.4142135623731>> (‐2) ** 0.5=> NaN
Цели числа42 ; ‐271 ; 1_024
Низове“bacon” ; ‘food’
С плаваща запетая3.1415 ; 2.71
Булеви данниtrue ; false
Масиви[2, 3, 5, 7, 11]
Хешове{‘one’ => 1, ‘two’ => 2}
Регулярни изрази/(bb)|([^b]{2})/
Области2..6 ; ‘a’...’z’
Символи:name ; :send ; :diff
Ламбдиlambda { |x| x ** 2 }‐> x { x ** 2}
ОбектиPerson.new
Нищо
nil != 0nil != false
‘Chunky bacon, I say!’“Who is John Galt?”“We’re the knights who say \”Ni!\””‘\’O freddled gruntbugly\’ he begun’‘This text contains\nno newlines’“This text contains\na newline”
Текст
>> “Hello,” + “ “ + “chunky!”=> “Hello, chunky!”>> “Ha! ” * 3=> “Ha! Ha! Ha!”>> “%s bacon” % ‘Chunky’=> “Chunky bacon”>> text = “Chanky”>> text[2] = ‘u’>> text << “ bacon”>> puts textChunky bacon
Операции с тект
Mutable
Mutable
>> original = “Chanky”>> text = original>> text[2] = ‘u’>> text << “ bacon”>> puts originalChunky bacon
“bacon\n”.chop # “bacon”“bacon”.chop # “baco”“bacon\n”.chomp # “bacon”“bacon”.chomp # “bacon”“Goodbye”.include? “oo” # true“foo”.replace “bar” # “bar”“oat”.insert 0, “bl” # “bloat”“Danube”.length # 6“bloat”.sub “bl”, “m” # “moat”“bacon”.upcase # “BACON”“BaCon”.downcase # “bacon”
Още операции с текст
text = “Chasin the Trane”text[2] # 116 или ‘t’text[2, 3] # ‘asi’text[2..3] # ‘as’text[‐5..‐1] # ‘Trane’text[‐5...‐1] # ‘Tran’text[/\w\we/] # ‘the’text[/the (\w+)/, 1] # ‘Trane’text[‘Trane’] # ‘Trane’text[‘rock’] # nil
alias :[] :slice
Швейцарско ножче []
>> answer = 42>> character = “Arthur Dent”>> puts “He had it: %s” % answerHe had it: 42>> puts “#{character} had it: #{answer}”Arthur Dent had it: 42>> puts “#{character} had it: #{6 * 9 ‐ 12}”Arthur Dent had it: 42>> puts ‘He had it: #{6 * 9 ‐ 12}’He had it: #{6 * 9 – 12}
Субституция
** ~ / % + ‐ &<< >> | ^ > < >= <= <=>&& || ! and or not ||= &&== += ‐= *= /= %= **= >>= <<=^= &= |= .. ... defined?
Оператори
Булева аритметика
To say of what is, that it is, or of what is not, that it is not, is true.
‐ Aristotle
Truth, in matters of religion, is simply the opinion that has survived.
‐ Oscar Wilde
I am the way, the truth, and the life: no man cometh unto the Father, but by me.
‐ Jesus, John 14:6
&& || !and or not
>> hungry = true>> sad = false>> puts hungry || sadtrue>> puts hungry && sadfalse>> puts !hungryfalse
>> hungry = true>> sad = false>> puts hungry or sadtrue>> puts hungry and sadfalse>> puts not hungryfalse
>> 20 > 20true>> “java” < “ruby”true>> 5 <= 5true>> “foo” <=> “bar”1
Сравнение
one == twoone.equal? twoone === twoone.eql? two
Равенство
== equal?
>> one = “chunky bacon”>> two = “chunky bacon”>> one == twotrue>> one.equal?(two)false>> one, two = 42, 42>> one == twotrue>> one.equal?(two)true
===
eql?
if hungry and sadeat_chocolatelisten_to_musicgo “outside”
end
if hungry and sad; eat_chocolate; end
if hungry and sadeat_chocolate
elseputs “I will manage... somehow”
end
if likes(“ruby”)puts “Gimme five!”
elsif likes(“python”) or likes(“perl”)puts “I guess you’re OK”
elsif likes(“basic”)puts “Did the lobotomy hurt?”
elseputs “What do you like, akshully?”preference = gets
end
name_shown = if logged_in?current_user.name
else“Unregistered user”
end
name = logged_in? ? user.name : “???”
unless error_occuredshow “Everything went Okey‐Dokey”do_stuff
end
while unhappy or not job.done?write_coderest
end
until job.done?write_coderest
end
>> numbers = [2, 3, 5, 8, 11]>> puts numbers[3]8>> numbers[3] = 7>> puts numbers[3]7>> puts numbers[7]nil>> numbers[7] = ‐42>> puts numbers.inspect[2, 3, 5, 7, 11, nil, nil, ‐42]
>> student = [“Stefan”, nil, 42]>> info = [[“Stefan”, 42],[“Nikolay”, 1729],[“Dimitur”, ‐271]
]
Масиви
>> numbers = [2, 3, 5, 7, 11]>> numbers.first2>> numbers.last11>> numbers[1, 3][3, 4, 5]>> numbers[1..2][3, 4]>> numbers[2, 2] = [6, 9, 6][2, 3, 6, 9, 6, 11]
Операции с масиви
>> [1, 2, 3, 2, 1].uniq[1, 2, 3]>> [“foo”, nil, “bar”].compact[“foo”, “bar”]2>> [1, 2] * 3[1, 2, 1, 2, 1, 2]>> [1, 2] + [3, 4][1, 2, 3, 4]>> [1, 2, 3, 4, 2] – [4, 2][1, 3]
Операции с масиви
>> numbers = [3, 4, 5]>> numbers.pop5>> numbers[3, 4]>> numbers.push 9[3, 4, 9]>> numbers[3, 4, 9]
Операции с масиви
>> numbers = [3, 4, 5]>> numbers.shift3>> numbers[4, 5]>> numbers.unshift 1[1, 4, 5]>> numbers[1, 4, 5]
Операции с масиви
Цикли
numbers = [2, 3, 5, 7]numbers.each do |n|puts “#{n} squared: #{n ** 2}”
end
2 squared: 43 squared: 95 squared: 257 squared: 49
масив.each do |променлива|блок
end
масив.each { |п| код }
>> numbers = [2, 3, 5, 7]
>> numbers.map { |x| x ** 2 }[4, 9, 25, 49]
>> numbers.select { |x| x > 4 }[5, 7]
numbers = [2, 3, 5, 7]for n in numbersputs “#{n} squared: #{n ** 2}”
end
2 squared: 43 squared: 95 squared: 257 squared: 49
numbers = [2, 3, 5, 7]for n in numbersputs “#{n} squared: #{n ** 2}”
end
2 squared: 43 squared: 95 squared: 257 squared: 49
Хешове
>> first_names = {“Coltrane” => “John”,“Vedder” => “Eddie”,“Davis” => “Miles”,“Rollins” => “Sonny”,
}>> first_names[“Coltrane”]“John”>> first_names[“Armstrong”]nil
>> first_names = {“Coltrane” => “John”,“Vedder” => “Eddie”,“Davis” => “Miles”,“Rollins” => “Sonny”,
}>> first_names[“Coltrane”]“John”>> first_names[“Armstrong”]nil>> first_names[“Evans”] = “Bill”
>> first_names.has_key? “Evans”true>> first_names.fetch “Mo”, “???”“???”>> first_names.keys[“Coltrane”, “Vedder”, “Davis”,“Rollins”, “Evans”]
>> first_names.values[“John”, “Eddie”, “Miles”,“Sonny”, “Bill”]
first_name.each do |last, first|puts “#{first} #{last}”
end
Функции
def име(аргументи)блок
end
def factorial(n)return 1 if n <= 1factorial(n ‐ 1) * n
end
def factorial(n)if n <= 11
elsefactorial(n – 1) * n
endend
Въпроси