http://tryruby.org/ http://www.ruby-lang.org/en/documentation/ http://www.ruby-lang.org/en/documentation/quickstart/1/ http://www.ruby-lang.org/en/documentation/quickstart/2/ http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/ irb def say_hello(name) puts "Hi, #{name}." end true/false/nil # When tested for truth, only false and nil evaluate to a false value. Everything else is true (including 0, 0.0, "", and []). 0, 0.0, "", [] ==> true elsif require (not import) instead of deleting variables, you can set it to nil class Greeter def initialize(name = "World") @name = name end def say_hi puts "Hi #{@name}" end def say_bye puts "Bye #{@name}" end end g = new Greeter.new("Pat") g.say_hi g.say_bye Greeter.instance_methods Greeter.instance_methods false Greeter.instance_methods(false) g.respond_to?("name") => false g.respond_to?("say_hi") => true g.respond_to?("to_s") => true #open up the class again class Greeter attr_accessor :name end g.name g.name = "Betty" g.say_hi 40.to_s.reverse "40".to_i #to integer "40".to_a #to array [12,43,35] [12,43,35].max ticket = [12, 13, 45] ticket ticket.sort x = "hello world" print x x["hello"] = "bob" print x "hello world".lines.to_a poem.lines.reverse poem.reverse print poem.lines.to_a.reverse.join books = {} books["Gravity's Rainbows"] = :splendid books["book two"] = :quite_not_good books["book three"] = :quite_good books["book four"] = :mediocre books.keys ratings = Hash.new{0} >> books.values.each { |rate| ratings[rate] += 1 } => [:splendid, :quite_good, :quite_not_good] #another block 5.times{ print "0delay!" } #symbols, tiny efficient code with words with a colon :splendid Dir.entries "/" print "pre", "event", "ual", "ism" Dir["/*.txt"] => ["#/comics.txt"] print File.read("/comics.txt") FileUtils.copy('/comics.txt', '/Home/comics.txt') File.open("/Home/comics.txt", "a") do |f| f << "Cat and Girl: http://catandgirl.com/\n" end print File.read("/Home/comics.txt") File.mtime("/Home/comics.txt") File.mtime("/Home/comics.txt").hour def load_comics(path) comics = {} File.foreach(path) do |line| name, url = line.split(": ") comics[name] = url.strip end comics end comics = load_comics("/comics.txt") Dir["/Libraries/*"] Popup.goto "http://google.com/" Popup.make { h1 "My links" link "Go to google", "http://google.com" } Popup.make do h1 "Things to do" list do p "Try out ruby" p "Ride a tiger" p "Ride the lightning" end end Popup.make do h1 "Comics on the web" list do comics.each do |name, url| link name, url end end end Hash.new blah = {} blah = Hash.new class BlogEntry attr_accessor :title, :time, :fulltext, :mood end entry = BlogEntry.new entry.title = "Today, Mt. Hood was stolen." entry.time = Time.now entry.mood = :sick entry * class BlogEntry * def initialize( title, mood, fulltext ) * @time = Time.now * @title, @mood, @fulltext = title, mood, fulltext * end * end blog = [entry1, entry2] blog.map { |entry| entry.mood } blog.each do |entry| h2 entry.title p entry.fulltext end #say you wanted to replace each of your blog entries with bruce willis: blog.map{ "Bruce Willis" } Time.now - 2.weeks http://rubyonrails.org/screencasts #ruby from other languages http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/ http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/ http://rubylearning.com/ http://www.techotopia.com/index.php/Ruby_Essentials http://www.meshplex.org/wiki/Ruby/Ruby_on_Rails_programming_tutorials http://en.wikibooks.org/wiki/Ruby_programming_language http://www.ruby-doc.org/docs/ProgrammingRuby/ http://www.rubyist.net/~slagell/ruby/ ruby tutorial http://rubylearning.com/satishtalim/tutorial.html $0 => name of the file ruby is executing $: => $PATH for ruby modules $$ => ruby process id #basic input/output puts => write to screen gets => get a string chomp => remove whitespaces from string on ends STDOUT.flush => flushes any buffered data within io to the underlying operating sstem. Not mandatory, but recommended. @blah => an instance variable of an object @@blah => a class variable, shared with all instances of the class $blah => a global variable. see also $_ and $-K. class names & module names are constants method name suffixes: ?, !, = ! labels a method as dangerous (see "bang methods") THIS_IS_A_CONSTANT ThisIsAClass this_is_a_variable 'i love ruby'.length puts Float::DIG puts Float::MAX rice_on_square = 1 64.times do |square| puts "On square #{square + 1} are #{rice_on_square} grain(s)" rice_on_square *= 2 end #small numbers Fixnum #large numbers Bignum s = 'hello' s.class #String puts "I am in class = " + self.class.to_s #Object puts "I am in class = " + self.to_s #main puts self.private_methods.sort self.private_methods.sort 5.times { puts "Mice!\n" } 5.times do |num| puts num #newlines end 5.times do |num| print num #no newlines end def return_hello 'Hello' end puts hello def return_hello(name) 'Hello ' + name end def hello2 name2 'Hello ' + name2 end puts hello2 'talim' # def mtd(arg1="Dibya", arg2="Shashank", arg3="Shashank") # "#{arg1}, #{arg2}, #{arg3}." # end # puts mtd # puts mtd("ruby") puts "100 * 5 = #{100 * 5}" alias new_method_name old_method_name #Local variables, instance variables, class variables, and constants may not be aliased. #variable number of parameters def foo(*my_string) my_string.each do |words| words end end puts foo('hello','world') puts foo() def opt_args(a,b,*x) # right def opt_args(a,*x,b) # wrong #you can add to the parameters def mtd(a=99, b=a+1) [a,b] end puts mtd string = "HELLO WORLD" string.downcase #"hello world" string.downcase! #returns "hello world" and modifies the object in place examples of bang methods: sort/sort! upcase/upcase! downcase/downcase! chomp/chomp! reverse/reverse! my_array.empty? => true/false my_number.nonzero? => true/false ri (ruby index) rdoc (ruby documentation) ri Array ri Array.sort ri Hash#each ri Math:sqrt String.methods.sort shows you a list of methods that the Class object String responds to. String.instance_methods.sort This method tells you all the instance methods that instances of String are endowed with. String.instance_methods(false).sort With this method, you can view a class's instance methods without those of the class's ancestors. s1 = "bryan" s2 = "bryan" if s1 == s2 puts "they are equal end if s1.eql?(s2) puts 'they have identical content' end if s1.equal?(s2) puts 'they are the same objects end #quick way to make an array of words names = %w{ bryan joe dave anna steve boton } names[0] unless ARGV.length == 2 puts "blah blah blah" end #loops var = 0 while var < 10 puts var.to_s var += 1 end (condition) ? (result if condition is true) : (result if condition is false) age = 15 puts (14...20).include?(age) ? "teenager" : "not a teenager" puts "Enrollments will now Stop" if participants > 2500 1. year = 2000 2. leap = case 3. when year % 400 == 0 then true 4. when year % 100 == 0 then false 5. else year % 4 == 0 6. end 7. puts leap 8. # output is: true year = 2000 leap = case when year % 400 == 0 then true when year % 100 == 0 then false else year % 4 == 0 end puts leap #output is: true NIL is a synonym for nil nil.class puts nil.object_id FALSE.class false.class puts false.object_id #single braces for blocks on a line { } #multi-line blocks have do & end greet {puts 'Hello'} verbose_greet("PuneRuby") {puts 'Hello'} =begin Blah =end def call_block puts 'Start of method' yield yield puts "End of method" end call_blcok {puts 'In the block'} #irb(main):090:0> call_block {puts "In the block"} #Start of method #In the block #What the hell? #In the block #End of method If you provide a code block when you call a method, then inside the method, you can yield control to that code block - suspend execution of the method; execute the code in the block; and return control to the method body, right after the call to yield. If no code block is passed, Ruby raises an exception with a LocalJumpError. def call_block yield('hello, 99) end call_block {|str,num| puts str + " " + num.to_s} def try if block_given? yield else puts "no block" end end try # => "no block" try { puts "hello } # => "hello" try do puts "hello" end # => "hello" x = 10 5.times do |x| puts "x inside the block: #{x}" end 5.times { |x| puts "x is: #{x}" } x = 10 5.times do |y| x = y puts "x inside the block: #{x}" end puts "x outside the block: #{x}" #block local variables, to shield a block from manipulating variables outside of its scope x = 1200 puts "Before the loop, x = #{x}" 3.times do |y;x| puts "Looping #{y}" x = y end puts "After the loop, x = #{y}" languages = ["english", "russian", "mandarin", "japanese", "german"] languages.each do |lang| puts "go study #{x}" end languages.delete("mandarin") languages.add("mandarin") #you can return multiple parameters def multiple_returns 10.times do |num| square = num * num return num, square if num > 5 #this will only be written out six times puts "after return, num is: #{num}" end end num, square = multiple_returns a = 1, 2, 3, 4 a = [1, 2, 3, 4] a, b = 1, 2, 3, 4 # => a == 1, b ==2 c, = 1, 2, 3, 4 # => c == 1 ENV.each {|k,v| puts "#{k}: #{v}" } #change the environmental variable for this process and child processes #(this doesn't change the parent process' environment variables) ENV["course"] = "whatever" #get the first argument f = ARGV[0] puts f 1. require 'getoptlong' 2. 3. # Call using "ruby tsftpc.rb -hftp.ibiblio.org -n21 -uanonymous -ps@s.com" 4. # The parameters can be in any order 5. unless ARGV.length == 4 6. puts "Usage: ruby tsftpc.rb -hftp_site_url -nport_no -uuser_name -ppassword" 7. exit 8. end 9. 10. host_name = port_no = user_name = password = '' 11. # specify the options we accept and initialize 12. # the option parser 13. opts = GetoptLong.new( 14. [ "--hostname", "-h", GetoptLong::REQUIRED_ARGUMENT ], 15. [ "--port", "-n", GetoptLong::REQUIRED_ARGUMENT ], 16. [ "--username", "-u", GetoptLong::REQUIRED_ARGUMENT ], 17. [ "--pass", "-p", GetoptLong::REQUIRED_ARGUMENT ] 18. ) 19. # process the parsed options 20. opts.each do |opt, arg| 21. case opt 22. when '--hostname' 23. host_name = arg 24. when '--port' 25. port_no = arg 26. when '--username' 27. user_name = arg 28. when '--pass' 29. password = arg 30. end 31. end str = 'hello' print Array(str).class #Array a = [1,2,3,4] print a.class.ancestors #ranges (1..14).to_a digits = -1..9 digits.include?(5) digits.min digits.max digits.reject {|i| i < 5} #use three '=' to test for interval inclusion (1..10) === 5 #true ('a'..'j') === 'z' #false ('a'..'z') === 'r' #true #symbols? :symbol.object_id :symbol2.object_id Symbol.all_symbols puts "string".to_sym.class #Symbol :symbol.to_s.class #String :symbol.class #Symbol #using symbols as hash keys #http://rubylearning.com/satishtalim/ruby_hashes.html #http://rubylearning.com/blog/2007/11/26/akitaonrails-on-ruby-symbols/ Symbol.new "hello world".to_sym :"hello world" params = { "id" => 1, "action" => "show" } #if you're using ActiveSupport params.symbolize_keys! #=> {:id=>1, :action=>"show"} #using symbols as keys in hashes person_data = Hash.new person_data[:name] = "Bryan Bishop" person_data[:language] = "English" puts person_data[:name] h = {:name => "Bryan Bishop"} rand(10) rand(100) require 'find' Find.find('./') do |f| type = case when File.file?(f) then "F" when File.directory?(f) then "D" else "?" end puts "#{type}: #{f}" end f = File.new("something_that_exists.rb") # SEEK_CUR - Seeks to first integer number parameter plus current positio # SEEK_END - Seeks to first integer number parameter plus end of stream # (you probably want a negative value for first integer number parameter) # SEEK_SET - Seeks to the absolute location given by first integer number parameter # :: is the scope operator - more on this later f.seek(12, IO::SEEK_SET) print f.readline f.close #object serialization #http://rubylearning.com/satishtalim/object_serialization.html Marshal.dump Marshal.load #regular expressions http://rubylearning.com/satishtalim/ruby_regular_expressions.html #writing your own classes http://rubylearning.com/satishtalim/writing_our_own_class_in_ruby.html "hello".methods.sort "hello".object_id "hello".to_sym.object_id if "hello".respond_to?("talk") "hello".talk end "hello".class.to_s "hello".instance_of? String Dog#bark #instance method bark of class Dog Dog.color #class method color of the class Dog Dog::color #class method #how to catch a NoMethodError #add method_missing to the class class Dummy def method_missing(m, *args, &block) puts "There's no method called #{m} here -- please try again." end end Dummy.new.anything #mobile blocks of code (Proc) prc = lambda {"hello"} puts prc.call toast = lambda do "hello" end toast.call def caller(some_proc) puts "Starting the caller." some_proc.call puts "Stopping the caller." end caller toast aBlock = lambda { |x| puts x } aBlock.call "Hello world" #load a file every time you call it load 'hello.rb' #load a file only once #ruby can load a shared library (like .so) if necessary require 'hello' #force ruby to load the module from the current directory, instead of just anywhere in $: require_relative 'hello' "blah".writesize class String def writesize self.size end end "how big am i?".writesize #see 'mammals.rb' class Mammal def initialize @name = "typical mammal" end def speak puts "what does the mammal say?" end def fly puts "mammal is flying" end end class Penguin < Mammal def initialize super @name = @name + ": ... penguin" end def speak puts "quack quack goes the {#@name}" end def fly puts "i'd rather swim" end end p = Penguin.new p.speak p.fly class Blah def method1 puts "first version" end def method1 puts "second version" end end #method1 (the second time) prevails module BasicFoo def foo(bar) puts "my foo is: {#bar}" end end class MehFoo include BasicFoo end modul = Module.new { methodNames.new { |x| define_method(m, klass.instance_method(m)) if klass.method_defined?(m)}} #inheritance? http://stackoverflow.com/questions/2556118/personal-method-in-ruby/