The beauty of Ruby through examples

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

I take it rand() gets pseudorandom numbers from computer and as such
could be improved in one respect at least if ruby can be made to sleep
or wait for random numbers of milliseconds. One complication with
random number generation is that two numbers can come off the belt in
the same millisecond. However making ruby wait a random number of
milliseconds between each sample draw sample draw is the random numbers
to provide the user would solve that problem. I just found the Pickaxe
book the other day and am reading through it and learning. The thing I
don't know is how much solving this problem with pseudorandom numbers
would improve quality of samples.

···

-----Original Message-----
From: Adriano Ferreira [mailto:adrfer@yahoo.com]
Sent: Wednesday, September 29, 2010 14:41
To: ruby-talk ML
Subject: The beauty of Ruby through examples

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

Adriano Ferreira wrote:

Any more examples?

For wow factor, I think you can't beat a 4-line webserver written in
Sinatra.

require 'sinatra'
get '/' do
  'Hello, world!'
end

···

--
Posted via http://www.ruby-forum.com/\.

Hi.

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.

In a presentation I made sometime ago, I used these at the beginning :

File.open("script.rb") do |fichier|
  fichier.each do |ligne|
    if ligne.downcase.include? "ruby"
      puts ligne
    end
  end
end

File.open("script.rb") do |f|
  f.each { |l| puts l if l=~/ruby/i }
end

# The Lottery here is 7 out of 36 balls.
(1..36).sort_by { rand }.slice(0,7).join(', ')

fct1 = lambda { |v| v.split(/ /).
          collect { |z| z.capitalize }.join(' ') }
fct2 = lambda { |v| v.split(//).
          collect { |c| c.ord }.join(',') }
         
fct1.call("this is a nice string.")
fct2.call("this is another nice string.")

require "open-uri"
open('http://www.google.com/'\) { |f| puts f.read }

HTH,

Fred

···

Le 29 septembre 2010 à 20:40, Adriano Ferreira a écrit :
--
She rules until the end of time
She gives and she takes
She rules until the end of time
She goes her own way (Within Temptation, Mother Earth)

def printTree(tree,indent)
if (Array === tree)
     tree.map { |child| printTree(child,indent+"| ") }
else
     puts(indent.gsub(/\s+$/,"--")+tree.to_s)
end
end
printTree([1,2,[11,22,[111,222,333,444],33],3,4],"")

this give :

···

--1

>--2
> >--11
> >--22
> > >--111
> > >--222
> > >--333
> > >--444
> >--33
>--3
>--4
--
Posted via http://www.ruby-forum.com/\.

# 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!

Wow, these are fantastic, especially this last one. I don't know if
this syntax (def padawan.control_the_force) has always been available
but I have long been doing that in a much more complicated way.

Please post your full list or your slides when you are finished! So
often people ask me "what's so great about Ruby" and I can't put it
into just a few sentences!

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]

···

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

[Note: parts of this message were removed to make it a legal post.]

I've been collecting some from around the internet, but i'd

appreciate your suggestions as well.

I started some samples to easily reply to the (programmers) guys
who ask me "Why Ruby?".

    http://www.ensta.fr/~diam/ruby/index.php?id=survie

I would be a good idea to build one or several page (wiki?)
in the style of:
  PLEAC-Ruby
but with your need in mind!

-- Maurice

···

On Sep 29, 8:40 pm, Adriano Ferreira <adr...@yahoo.com> wrote:

So am I, I will give a lightning talk about Ruby in a week.

Do you have any objection if I use some of the examples of this thread ?

It is not easy to find awesome examples when you are used to them, I
got a hard time finding some.

Best Regards,
B.D.

···

On 29 September 2010 20:40, Adriano Ferreira <adrfer@yahoo.com> wrote:

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 presented about Ruby last night to my school for the ACM at my school, had
a few examples to show OO and functional paradigms, and an example to show
that it is dynamic. We also did a rails example, we were giving away a 4gb
thumb drive, and so made a Rails app to select a winner from a list of
contestants, then put it on Heroku and let them go sign up for it
themselves.

Here were my code examples

And video of the presentation

One thing I'll suggest is to have the code already printed out and sitting
next to you. Then you can have that organic feel of writing it right there,
which I think makes it easier to follow. But you can also save yourself a
lot of headache of forgetting something when coding live. I'll also suggest
against a Rails example, because there is a lot of stuff going on in Rails,
you have to keep lots of different things in your brain all at once, which
is difficult to do while you are presenting, and I think the Rails example
was the slowest part of the presentation.

···

On Wed, Sep 29, 2010 at 1:40 PM, Adriano Ferreira <adrfer@yahoo.com> wrote:

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

What about a one-line HTTP server written in Lua? :stuck_out_tongue:

HTTP[ '/' ] = function() return 'Hello world' end TCPServer( '127.0.0.1', 1080 )( HTTP )

···

On Sep 29, 2010, at 9:07 PM, Brian Candler wrote:

For wow factor, I think you can't beat a 4-line webserver written in
Sinatra.

F. Senault wrote:

File.open("script.rb") do |fichier|
  fichier.each do |ligne|
    if ligne.downcase.include? "ruby"
      puts ligne end
  end
end

File.open("script.rb") do |f|
  f.each { |l| puts l if l=~/ruby/i }
end

It's worth mentioning this, too:

puts `grep -i ruby script.rb`

And I forgot a simple, classic, one :

def factorial(n)
  (1..n).inject(1) { |p, f| p * f }
end

def factorial(n)
  (1..n).inject(1, :*)
end

(I don't like much the second one, it's a bit less legible.)

Fred

···

Le 29 septembre à 21:26, F. Senault a écrit :

--
When my body starts to shiver from the chill of The scarlett sweat
When my lips eclipse the sun and the moon Reflecting from the wet When
the blood of my love outraces Every one of the stallions in your pack -
that's when U go, u go, u go 2 the max (Prince, The Max)

Threading is light in ruby, so here a try show works in paralleles :

require 'thread'
require 'socket'
require 'timeout'

############### Send a file by socket to www server

def send_file(hostname,filename)
timeout(3+File.size(filename)/10000) { # timeout, in seconds
   socket=TCPSocket.open(hostname,80)
   socket.write( "POST /upload/#{filename} HTTP/1.1\r\n\r\nContent=" )
   socket.write( IO.read(filename) )
   print "\n#{filename} transfered"
}
rescue Exception => ex
puts "ERROR on transfert #{filename} to {hostname} : #{ex}"
ensure
socket.close rescue nil # anyway, try to close
end

################### MAIN : send *.rb in //

threads= Dir["*.rb"].map do |file|
  sleep(0.1) while Thread.list.size>20
  Thread.new { send_file(ARGV[0],file) }
end
threads.each {|thread| thread.join} # wait all finish before exit

Attachments:
http://www.ruby-forum.com/attachment/5114/beauty.rb

···

--
Posted via http://www.ruby-forum.com/.

IMO this is more idiomatic:

class Object
   def recursive_print indent = ""
     puts indent.gsub(/\s+$/,"--") + to_s
   end
end

module Enumerable
   def recursive_print indent = ""
     map { |child| child.recursive_print indent+"| " }
   end
end

[1,2,[11,22,[111,222,333,444],33],3,4].recursive_print

···

On 09/30/2010 07:48 AM, Regis d'Aubarede wrote:

def printTree(tree,indent)
  if (Array === tree)
      tree.map { |child| printTree(child,indent+"| ") }
  else
      puts(indent.gsub(/\s+$/,"--")+tree.to_s)
  end
end
printTree([1,2,[11,22,[111,222,333,444],33],3,4],"")

[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:

(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/

···

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:

I would be a good idea to build one or several page (wiki?)
in the style of:
PLEAC-Ruby
but with your need in mind!

This site seems to have a few stylistic problems, as far as common
idiomatic Ruby goes. For instance there's a lot of ignoring #each in
http://pleac.sourceforge.net/pleac_ruby/arrays.html

Might not be the best introduction to Ruby for someone.

···

On Sun, Oct 3, 2010 at 10:20 AM, mdiam <maurice.diamantini@gmail.com> wrote:

On Sep 29, 8:40 pm, Adriano Ferreira <adr...@yahoo.com> wrote:

[Note: parts of this message were removed to make it a legal post.]

I've been collecting some from around the internet, but i'd

appreciate your suggestions as well.

I started some samples to easily reply to the (programmers) guys
who ask me "Why Ruby?".

http://www.ensta.fr/~diam/ruby/index.php?id=survie

I would be a good idea to build one or several page (wiki?)
in the style of:
PLEAC-Ruby
but with your need in mind!

-- Maurice

If you're on OSX, I think this makes for a great example, though I usually
take out the command line args and set the username and password in another
file that I require.

···

On Tue, Oct 19, 2010 at 2:11 PM, Benoit Daloze <eregontp@gmail.com> wrote:

On 29 September 2010 20:40, Adriano Ferreira <adrfer@yahoo.com> wrote:
> 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.
>

So am I, I will give a lightning talk about Ruby in a week.

Do you have any objection if I use some of the examples of this thread ?

It is not easy to find awesome examples when you are used to them, I
got a hard time finding some.

Best Regards,
B.D.

I guess you should show irb explicitly.

Another thing worth pointing out: the Ruby source tarball is about 1/3
of the size of Perl, but you get a whole load more libraries by default:
openssl, https, md5/sha1 digests, readline, tk, dbm, ...

···

--
Posted via http://www.ruby-forum.com/.

yes, it's a one-liner, but, you'll have to _read_ it many times..
cheers -botp

···

On Thu, Sep 30, 2010 at 3:30 AM, Petite Abeille <petite.abeille@gmail.com> wrote:

What about a one-line HTTP server written in Lua? :stuck_out_tongue:

HTTP[ '/' ] = function() return 'Hello world' end TCPServer( '127.0.0.1', 1080 )( HTTP )