1. Introduction to Ruby
my_num = 25 my_boolean = true my_string = "Ruby" 3+3 3-3 3*3 3/3 3**3 3%3 puts "What's up" # newline print "Montalvo" "I love espresso".length "Eric".reverse puts "eric".upcase puts "ERIC".downcase puts "Eric".downcase.reverse.upcase =begin I'm a comment! I don't need any # symbols. =end print "What's your first name?" first_name = gets.chomp first_name.capitalize! puts "Your name is #{first_name}"2. Control Flow in Ruby
x = 1 y = 2 if x < y puts "x is less than y!" elsif x > y puts "x is greater than y!" else puts "x equals y!" end hungry = false unless hungry puts "I'm writing Ruby programs!" else puts "Time to eat!" end is_true = 2 != 3 is_false = 2 == 3 test_1 = 17 > 16 test_2 = 21 < 30 test_3 = 9 >= 9 test_4 = -11 <= 4 true && true # => true false || false # => false !true # => false (3 < 4 || false) && (false || true)3. Looping with Ruby
counter = 1 while counter < 11 puts counter counter += 1 end counter = 1 until counter > 11 puts counter counter += 1 end for num in 1...10 # 1-9 puts num end for num in 1..10 # 1-10 puts num end i = 20 loop do i -= 1 next if i % 2 != 0 print "#{i}" break if i <= 0 end my_array = [1,2,3,4,5] array = [1,2,3,4,5] array.each do |x| x += 10 print "#{x}" end odds = [1,3,5,7,9] odds.each do |n| print n*2 end 10.times { print "Chunky bacon!" }4. Arrays and Hashes
demo_array = [100, 200, 300, 400, 500] print demo_array[2] multi_d_array = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] multi_d_array.each { |x| puts "#{x}\n" } my_hash = { "name" => "Eric", "age" => 26, "hungry?" => true } puts my_hash["name"] puts my_hash["age"] puts my_hash["hungry?"] pets = Hash.new pets["Stevie"] = "cat" pets["John"] = "dog" pets.each { |x, y| puts "#{x}: #{y}" }5. Blocks and Sorting
def puts_1_to_10 (1..10).each { |i| puts i } end puts_1_to_10 def cubertino(n) puts n ** 3 end cubertino(8) def what_up(greeting, *bros) bros.each { |bro| puts "#{greeting}, #{bro}!" } end what_up("What up", "Justin", "Ben", "Kevin Sorbo") my_array = [3, 4, 8, 7, 1, 6, 5, 9, 2] my_array.sort! book_1 = "A Wrinkle in Time" book_2 = "A Brief History of Time" c = book_1 <=> book_2 # -1 (>), 0 (=), 1 (<)6. Hashes and Symbols
symbol_hash = { :symbol1 => 1, # symbol1: 1, :symbol2 => 2, # symbol2: 2, :symbol3 => 3 # symbol3: 3 } strings = ["HTML", "CSS", "JavaScript", "Python", "Ruby"] symbols = Array.new strings.each do |string| symbols.push(string.to_sym) # or string.intern end movie_ratings = { memento: 1, primer: 2, the_matrix: 3, } good_movies = movie_ratings.select { |m, r| r > 2 } movie_ratings.each_key { |k| puts k } movie_ratings.each_value { |v| puts v }7. Refactoring
ruby_is_eloquent = true ruby_is_ugly = false puts "Ruby is eloquent!" if ruby_is_eloquent puts "Ruby's not ugly!" unless ruby_is_ugly puts 1>0 ? "True" : "False" # Ternary conditional expression case greeting when "English" then puts "Hello!" when "French" then puts "Bonjour!" when "German" then puts "Guten Tag!" when "Finnish" then puts "Haloo!" else puts "I don't know that language!" end favorite_book = nil favorite_book ||= "Guide to Ruby" # set favorite_book ||= "Guide to Perl" # not set def add(a,b) return a + b # a + b (without return) end "L".upto("P") { |l| puts l } age = 26 age.respond_to?(:next) # true (27) alphabet = ["a", "b", "c"] alphabet << "d" # alphabet.push("d") caption = "A giraffe surrounded by " caption << "weezards!" # caption += "weezards!" age = 26 I am " + age.to_s + " years old." I am " << age.to_s << " years old." I am #{age} years old."8. Blocks, Procs, and Lambdas
fibs = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] doubled_fibs = fibs.collect { |f| f*2 } def double(p) yield p end double(1){ |x| x*2 } floats = [1.2, 3.45, 0.91, 7.727, 11.42, 482.911] round_down = Proc.new { |x| x.floor } ints = floats.collect(&round_down) hi = Proc.new { puts "Hello!" } hi.call numbers_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] strings_array = numbers_array.collect(&:to_s) strings = ["leonardo", "donatello", "raphael", "michaelangelo"] symbolize = lambda { |s| s.to_sym } symbols = strings.collect(&symbolize)9. Object-Oriented Programming, Part I
class Person def initialize(name) @name = name end end me = Person.new("Eric") class MyClass $my_variable = "Hello!" # global var end puts $my_variable class Person @@people_count = 0 # class variable def initialize(name,age,profession) @name = name # instance var @age = age @profession = profession end end class ApplicationError def display_error puts "Error! Error!" end end class SuperBadError < ApplicationError # inheritance def display_error # override puts "SuperError! SuperError!" super # call parent method end end err = SuperBadError.new err.display_error10. Object-Oriented Programming, Part II
class Dog def initialize(name,breed) @name = name @breed = breed end public def bark puts "Woof!" end private def id @id_number = 12345 end end module Circle PI = 3.141592653589793 def Circle.area(radius) PI * radius**2 end def Circle.circumference(radius) 2 * PI * radius end end puts Math::PI require 'date' puts Date.today module Action def jump @distance = rand(4) + 2 puts "I jumped forward #{@distance} feet!" end end class Rabbit include Action attr_reader :name def initialize(name) @name = name end end peter = Rabbit.new("Peter") peter.jump module ThePresent def now puts "Time" end end class TheHereAnd extend ThePresent end TheHereAnd.now
No comments:
Post a Comment