Notions de base la programmation de Ruby
.
Sortie
.
#!/usr/bin/ruby puts "Hello"
Variables
.
#!/usr/bin/ruby num = 5 # store a number to variable char = 'a' # store a single character string = "This is a string" # store a string puts "Number is #{num}" # output variable storing a number puts "Character is '#{char}'" # output variable storing a character puts "String is \"#{string}\"." # output variable storing a string
Constantes
.
#!/usr/bin/ruby PI = 3.145927 # initialize value puts PI PI = 3 # attempt to change value PI = PI + 1 # attempt to increment value puts PI
Arithmétique
.
#!/usr/bin/ruby # integer arithmatic width = 5 length = 6 area = width * length puts "The area of a square(width=#{width}, length=#{length}) is #{area}" # bolean logic result = true and false or true puts "The statement (true AND false OR true) is #{result}"
.
#!/usr/bin/ruby PI = 3.1415927 # approximation of π radius = 3 area = PI * radius ** 2 # calculate π * r^2 puts "The area of a circle is #{area}"
.
#!/usr/bin/ruby PI=3.14115927 # approximation of π puts "The cosine of pi/4 is: #{Math.cos(PI/4)}"
Entrée
.
#!/usr/bin/ruby print "Enter your name: " # print prompt STDOUT.flush # flush buffer, so that prompt shows name = gets # acquire string input print "Hello #{name}" # output result using variable
Choix
.
#!/usr/bin/ruby print "Input a number: " # print prompt $stdout.flush # flush unbuffered stream number = gets.chomp.to_i # acquire number (remove newline, convert to int) if number > 0 puts "Number is greater than 0" elsif number < 0 puts "Number is less than 0" else puts "Number is 0" end
.
#!/usr/bin/ruby print "Input a character: " # prompt STDOUT.flush # flush unbuffered stream keypress = STDIN.getc # acquire single character # test if keypress matches pattern result = case keypress when /[a-z]/ then "Lowercase letter" when /[A-Z]/ then "Uppercase letter" when /[0-9]/ then "Digit" else "Punctuation, whitespace, or other" end puts result
#!/usr/bin/ruby print "Input a character: " # prompt STDOUT.flush # flush unbuffered stream keypress = STDIN.getc # acquire single character # test if keypress matches pattern result = case keypress when /[a-z]/ then "Lowercase letter" when /[A-Z]/ then "Uppercase letter" when /[0-9]/ then "Digit" else "Punctuation, whitespace, or other" end puts result
.
#!/usr/bin/ruby print "Input a character: " # prompt STDOUT.flush # flush unbuffered stream keypress = STDIN.getc # acquire single character # test if keypress matches pattern if keypress =~ /[a-z]/ puts "Lowercase letter" elsif keypress =~ /[A-Z]/ puts "Uppercase letter" elsif keypress =~ /[0-9]/ puts "Digit" else puts "Punctuation, whitespace, or other" end
Boucles
Une boucle est une séquence d'instructions qui est spécifié une fois mais qui peut être réalisée plusieurs fois de suite. Ruby a de nombreuses constructions en boucle ainsi que les méthodes d'itération.
Voici cinq méthodes différentes pour compte à rebours de 10 à 1.
Voici cinq méthodes différentes pour compte à rebours de 10 à 1.
#!/usr/bin/ruby # while loop w/ counter count = 10 while count > 0 puts "Count is #{count}" count -= 1 end
#!/usr/bin/ruby # for loop w/ counter for count in (10).downto(0) do puts "Count is #{count}" end
#!/usr/bin/ruby # downto iterator w/ counter 10.downto(0) do | count | puts "Count is #{count}" end
#!/usr/bin/ruby # range in reverse (1..10).to_a.reverse.each do |count| puts "Count is #{count}" end
#!/usr/bin/ruby # iterate number of times, calculate opposite range 10.times do |count| puts "Count is #{(count-10)*-1}" end
Voici cinq méthodes différentes de boucle jusqu'à ce que l'utilisateur le choix de sortir de la boucle.
#!/usr/bin/ruby # loop until user quits (begin...while construct) begin print "Enter your name (quit to Exit): " # print prompt STDOUT.flush # flush buffer to show prompt answer = gets.chomp # get string input if answer != "quit" puts "Hello #{answer}" # print if not exiting end end while answer != "quit"
#!/usr/bin/ruby answer = "" # default # loop until user quits (while/do...end construct) while answer != "quit" do print "Enter your name (quit to Exit): " # print prompt STDOUT.flush # flush buffer to show prompt answer = gets.chomp # get string input if answer != "quit" puts "Hello #{answer}" # print if not exiting end end
#!/usr/bin/ruby # loop until user quits (begin...until construct) begin print "Enter your name (quit to Exit): " # print prompt STDOUT.flush # flush prompt to show prompt answer = gets.chomp # get string input if answer != "quit" puts "Hello #{answer}" # print if not exiting end end until answer == "quit"
#!/usr/bin/ruby answer = "" # default # loop until user quits (until/do...end construct) until answer == "quit" do print "Enter your name (quit to Exit): " # print prompt STDOUT.flush # flush buffer to show prompt answer = gets.chomp # get string input if answer != "quit" puts "Hello #{answer}" # print if not exiting end end
#!/usr/bin/ruby # loop until user quits (spin loop style) loop do print "Enter you name (quit to Exit): " # print prompt STDOUT.flush # flush buffer to show prompt answer = gets.chomp # get string input if answer.chomp == "quit" # check for exit break # exit loop else puts "Hello #{answer}" # print result if not exiting end end
Voici deux méthodes pour faire défiler une liste d'éléments. Ces extraits montrent aussi comment faire fonctionner un sous-processus et de tester les propriétés d'un fichier ou d'un répertoire.
#!/usr/bin/ruby # for/in w/ exec for item in `ls`.split.each do # cycle through directory listing if File.directory? item # test if path is directory puts "#{item} is a directory." else puts "#{item} is not a directory." end end
#!/usr/bin/ruby # each iterator w/ sub-process `ls`.split.each do |item| # cycle thorugh directory listing if File.directory? item # test if path is directory puts "#{item} is a directory." else puts "#{item} is not a directory." end end
Tableaux
.
#!/usr/bin/ruby # create empty array nicknames = Array.new # insert elements by index nicknames[0] = "bob" nicknames[1] = "ed" nicknames[2] = "steve" nicknames[3] = "ralph" nicknames[4] = "joe" nicknames[5] = "deb" nicknames[6] = "kate" # print length puts "The total nicknames are: #{nicknames.length}" # enumerate full list puts "The nicknames are: #{nicknames.join(" ")}"
#!/usr/bin/ruby # create populated array nicknames = %w(bob ed steve ralph joe deb kate) # iterate through array, one element at a time puts "The names are: " nicknames.each { |name| puts " #{name}" }
#!/usr/bin/ruby # create populated array nicknames = %w(bob ed steve ralph joe deb kate) # iterate through array by index puts "The names are: " nicknames.length.times { |count| puts " nicknames[#{count}]=#{nicknames[count]}"}
Tableaux associatifs
.
#!/usr/bin/ruby # create empty hash ages = Hash.new # insert one element at a time ages["bob"] = 34 ages["ed"] = 58 ages["steve"] = 32 ages["ralph"] = 23 ages["deb"] = 46 ages["kate"] = 19 # enumerate and print keys puts "Keys (names): #{ages.keys.join(" ")}" # enumerate and print values puts "Values (ages): #{ages.values.join(" ")}"
.
#!/usr/bin/ruby # initialize array with key/value pairs ages = {"bob"=> 34, "ed"=> 58, "steve"=> 32, "ralph"=> 23} # append another set of key/value pairs into array ages = ages.merge("deb"=> 46, "kate"=> 19) # iterate through hash by keys, print key/value pairs puts "The ages are: " ages.keys.each { |name| puts " ages[#{name}]=#{ages[name]}"}
#!/usr/bin/ruby # initialize array with key/value pairs ages = {"bob"=> 34, "ed"=> 58, "steve"=> 32, "ralph"=> 23} # append another set of key/value pairs into array ages = ages.merge("deb"=> 46, "kate"=> 19) # iterate through hash by key/value, print key/value pairs puts "The ages are: " ages.each { |name,age| puts " ages[#{name}]=#{age}"}