On Oct 2, 2010, at 10:25 AM, w_a_x_man wrote: > On Sep 29, 1:40 pm, Adriano Ferreira <adr... / yahoo.com> wrote: >> [Note: parts of this message were removed to make it a legal post.] >> >> Hey all, >> >> I'm about to introduce Ruby to a group of people that is not >> familiar to the >> language, and the approach i'd like to take is simply by distilling >> out a few >> sample codes. I've been collecting some from around the internet, >> but i'd >> appreciate your suggestions as well. >> >> I'm looking for code snippets that represent some of the beauty of >> Ruby >> actually, such as: >> >> # Simplicity >> # Expressiveness >> # Productivity >> # Flexibility >> # Dynamism >> # Freedom >> # Happiness >> >> Just to clear things up, here are few examples: >> >> # Simplicity >> >> vowels = %w(a e i o u) >> alfabet = ('a'..'z').to_a >> cons = alfabet - vowels >> p cons >> >> # Expressiveness >> >> hello = 'Hello Ruby' >> 5.times { puts hello } >> >> # Productivity >> >> class Person >> # def name >> # @name >> # end >> # >> # def name=(other) >> # @name = other >> # end >> # >> # def age >> # @age >> # end >> # >> # def age=(other) >> # @age = other >> # end >> >> attr_accessor :name, :age >> end >> >> john = Person.new >> john.name = 'John' >> john.age = 25 >> p john >> >> # Flexibility >> >> class Array >> def pick >> self[rand(self.size)] >> end >> >> alias :choose :pick >> end >> >> puts %w(1 2 3 4 5).pick >> puts %w(1 2 3 4 5).choose >> >> # Dynamism >> >> Padawan = Class.new >> >> class Jedi >> def train(padawan) >> def padawan.control_the_force >> puts "Now i'm ready to become a Jedi!" >> end >> end >> end >> >> skywalker = Padawan.new >> yoda = Jedi.new >> p skywalker.respond_to? :control_the_force # => false >> >> yoda.train skywalker >> p skywalker.respond_to? :control_the_force # => true >> skywalker.control_the_force# => Now i'm ready to become a Jedi! >> >> ..and so on. >> >> Any more examples? >> >> Thanks in advance, >> >> Adriano > > In comp.lang.lisp, this elisp code was posted as an example > of how to shuffle a vector: > > (defun emms-shuffle-vector (vector) > "Shuffle VECTOR." > (let ((i (- (length vector) 1))) > (while (>= i 0) > (let* ((r (random (1+ i))) > (old (aref vector r))) > (aset vector r (aref vector i)) > (aset vector i old)) > (setq i (- i 1)))) > vector) > > Ruby: > > (9..20).sort_by{ rand } > ==>[15, 14, 12, 18, 16, 10, 9, 13, 11, 20, 17, 19] > And in Ruby 1.9 it's even easier to shuffle and array: irb> (9..20).to_a.shuffle => [15, 11, 20, 10, 9, 18, 13, 19, 16, 17, 14, 12] -Rob Rob Biedenharn Rob / AgileConsultingLLC.com http://AgileConsultingLLC.com/ rab / GaslightSoftware.com http://GaslightSoftware.com/