The beauty of Ruby through examples

W

w_a_x_man

[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 afew
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]
 
R

Rob Biedenharn

[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
(e-mail address removed) http://AgileConsultingLLC.com/
(e-mail address removed) http://GaslightSoftware.com/
 
A

Adam Prescott

I would go with #first, since it's somewhat more readable.

How about some more simple ones like

'Do Re Mi Fa So La Ti ' * 3

[125, 450, 250, 1000, 675].sort.reverse.collect{|e| "$#{e}"}.take(3)

' =C2=A0 =C2=A0 =C2=A0hello there =C2=A0'.strip.center(30, '-')

[125, 450, 250, 1000, 675].sort.reverse.map{|e| "$#{e}"}[0,3]
=C2=A0 =C2=A0=3D=3D>["$1000", "$675", "$450"]
 
M

mdiam

[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:
http://pleac.sourceforge.net/pleac_ruby
but with your need in mind!

-- Maurice
 
A

Adam Prescott

I would be a good idea to build one or several page (wiki?)
in the style of:
=C2=A0http://pleac.sourceforge.net/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.

[Note: =C2=A0parts of this message were removed to make it a legal post.= ]
=C2=A0I'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?".

=C2=A0 =C2=A0http://www.ensta.fr/~diam/ruby/index.php?id=3Dsurvie

I would be a good idea to build one or several page (wiki?)
in the style of:
=C2=A0http://pleac.sourceforge.net/pleac_ruby
but with your need in mind!

-- Maurice
 
M

mdiam

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

Might not be the best introduction to Ruby for someone.

I agree!

That's why I said "in the style of": not the programming style, but
the web diffusion style (like a wiki).
A web page which has a stable and simple URL,
A web page which one can link to for several years.
-- Maurice
 
A

Adam Prescott

I agree!
That's why I said "in the style of": not the programming style, but
the web diffusion style (like a wiki).

Yes, I agree. Sorry, I wasn't objecting to what you said directly, as
such, but just generally flagging up some of the website's contents so
that other readers (hopefully) don't start writing camelCase.
 
G

Giampiero Zanchi

find the first gap in array of fixnum values

p [1,2,3,5,6,8,9,10].inject {|a, e| e == a.next ? e : (break a.next)}

will produce 4
 
A

Adam Prescott

I don't see this as much of a good use of inject, to be honest.

I'd rather see this:

numbers = [1, 2, 3, 4, 6, 7, 8, 9]
numbers.each_cons(2) { |x, y| break x if x.succ != y }

or to get rid of the need to explain how break works and what succ is,
while allowing more readability, perhaps

numbers = [1, 2, 3, 4, 6, 7, 9, 10] # has a gap after 4 and 7!
gaps = []
numbers.each_cons(2) do |x, y|
gaps << x unless y == x + 1
end

gaps #=> [4, 7]

You'll possibly have to explain each_cons, but I think it's easier
than explaining inject to someone who doesn't know Ruby or
programming. You also get to show off post-statement "unless"!
 
B

Benoit Daloze

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.
 
J

Josh Cheek

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

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.
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.
http://github.com/intridea/tweetstream/blob/master/examples/growl_daemon.rb
 
B

Benoit Daloze

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.
http://github.com/intridea/tweetstream/blob/master/examples/growl_daemon.rb

Seems cool, I tried a little, and found my screen full of Tweets !

However, I will not give the talk on my laptop, and it will be Linux.

But, I'll mention it as a cool use case.
Thanks for the link
 
J

Josh Cheek

[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
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
http://github.com/JoshCheek/PresentationFiles/tree/master/NightOfTheLivingRuby!/
And video of the presentation
http://www.vimeo.com/channels/nightofthelivingruby

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top