[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

a matter of style

Bas van Gils

6/11/2007 6:11:00 PM


All,

A little while ago I picked up a copy of the pickaxe book and got hooked to
Ruby. Never had a `real' project to work on though (that's what you get when
you don't hack for a living I suppose :-). Either way, a few weeks back I
needed an app that generates deals for the card game bridge. I made a small
design and hacked up some unit tests. After a while no more tests failed:

bas@Librarian { ~/bridgehands }$ ruby bridgeTests.rb
Loaded suite bridgeTests
Started
....
Finished in 0.003154 seconds.

After a bit more coding to format the output I got something that outputs:

bas@Librarian { ~/bridgehands }$ ruby deal.rb
AQJ652
92
T53
Q5
973 4
K87653 AQJ
8 J742
JT4 A9876
KT8
T4
AKQ96
K32

Not bad... Like I said, I'm not a full-time programmer. I would *love* to
learn more about `proper' ruby style though. Is there even such a thing? I
mean, the book cover said something about *pragmatic* :-)

Could anyone have a look at:

http://www.va.../~bas/br...

and give me some suggestions on style / ruby idiom / other things?

Any help would be greatly appreciated,

yours

Bas

--
Bas van Gils <bas@van-gils.org>, http://www.va...
[[[ Thank you for not distributing my E-mail address ]]]

Quod est inferius est sicut quod est superius, et quod est superius est sicut
quod est inferius, ad perpetranda miracula rei unius.


21 Answers

Anthony Martinez

6/11/2007 6:40:00 PM

0

On Tue, Jun 12, 2007 at 03:10:49AM +0900, Bas van Gils wrote:
>
> All,
>
> A little while ago I picked up a copy of the pickaxe book and got hooked to
> Ruby. Never had a `real' project to work on though (that's what you get when
> you don't hack for a living I suppose :-). Either way, a few weeks back I
> needed an app that generates deals for the card game bridge. I made a small
> design and hacked up some unit tests. After a while no more tests failed:
[snip]
> Not bad... Like I said, I'm not a full-time programmer. I would *love* to
> learn more about `proper' ruby style though. Is there even such a thing? I
> mean, the book cover said something about *pragmatic* :-)
>
> Could anyone have a look at:
>
> http://www.va.../~bas/br...
>
> and give me some suggestions on style / ruby idiom / other things?
>
> Any help would be greatly appreciated,

From what I've been led to understand, method names consisting of
multiple words should be named_with_underscores, not namedWithCamelcase.

`puts' is the same as `print "something\n"'

Parens can be omitted if it doesn't confuse the parser (or the reader)

As well, reserve the { } form of blocks to one-liners.

Taking these into account, instead of writing (from
http://www.va.../~bas/br...deal.rb):

bg.suits.each{ |suit|
cards = bg.north.cardsOfSuit(suit)
print " #{bg.sortCards(cards)} \n"
}

write something like

bg.suits.each do |suit|
cards = bg.north.cards_of_suit suit
puts " #{bg.sort_cards(cards)} "
end

Then again, these are highly subjective views, ones that I've absorbed
from reading other people's ruby and getting into arguments with friends
:) Take them with a grain of salt, as I'm not a Ruby expert and thus I
might be wrong.

>
> yours
>
> Bas
>
> --
> Bas van Gils <bas@van-gils.org>, http://www.va...
> [[[ Thank you for not distributing my E-mail address ]]]
>
> Quod est inferius est sicut quod est superius, et quod est superius est sicut
> quod est inferius, ad perpetranda miracula rei unius.
>
>

--
C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you
do succeed, you will blow away your whole leg.
-- Bjarne Stroustrup

Robert Dober

6/11/2007 6:58:00 PM

0

On 6/11/07, Bas van Gils <bas@van-gils.org> wrote:
>
> All,
>
> A little while ago I picked up a copy of the pickaxe book and got hooked to
> Ruby. Never had a `real' project to work on though (that's what you get when
> you don't hack for a living I suppose :-). Either way, a few weeks back I
> needed an app that generates deals for the card game bridge. I made a small
> design and hacked up some unit tests. After a while no more tests failed:
>
> bas@Librarian { ~/bridgehands }$ ruby bridgeTests.rb
> Loaded suite bridgeTests
> Started
> ....
> Finished in 0.003154 seconds.
>
> After a bit more coding to format the output I got something that outputs:
>
> bas@Librarian { ~/bridgehands }$ ruby deal.rb
> AQJ652
> 92
> T53
> Q5
> 973 4
> K87653 AQJ
> 8 J742
> JT4 A9876
> KT8
> T4
> AKQ96
> K32
Do not forget to unblock the Ten of Diamonds in your 4 Spades ;)
>
> Not bad... Like I said, I'm not a full-time programmer. I would *love* to
> learn more about `proper' ruby style though. Is there even such a thing? I
> mean, the book cover said something about *pragmatic* :-)
>
> Could anyone have a look at:
>
> http://www.va.../~bas/br...

Some thaughts
(*) why do you define Player#setName! an attribute accessor to :name
seems appropriate
(*) Card = Struct.new( :suit, :face ) would be sufficent
(*) Ruby allows for much shorter code, look e.g at
def getCard
if @cards.size == 0
raise "No more cards in the deck"
end
return @cards.slice!(0)
end
which I would write as
def getCard;
@cards.shift or raise SomeNiceErrorClass, "No more cards in the deck"
end
(+) An example where you are in harmony with ruby is:
def cardsOfSuit(sn)
return @cards.select{ |card| card.suit.name==sn }
end
The return however is superfluous, but it is a respectable style to
end all defs with return statements

(*) Personally I think it is nice to name CardSet#shuffle! with the
"!". However more learned members of the community think that the
existance of X#member! implies
X#member and X#member is to be defined as

def member; x = dup; x.member!; x end

Just to let you know, I am with you but we are pretty alone ;)

All at all pretty impressive for a beginner.

Cheers
Robert
>
> and give me some suggestions on style / ruby idiom / other things?
>
> Any help would be greatly appreciated,
>
> yours
>
> Bas
>
> --
> Bas van Gils <bas@van-gils.org>, http://www.va...
> [[[ Thank you for not distributing my E-mail address ]]]
>
Robert

--
You see things; and you say Why?
But I dream things that never were; and I say Why not?
-- George Bernard Shaw

Bas van Gils

6/12/2007 6:34:00 AM

0


Hi all

Robert (and also Anthony), thanks for your comments!

On Tue, Jun 12, 2007 at 03:58:21AM +0900, Robert Dober wrote:
> (*) Card = Struct.new( :suit, :face ) would be sufficent

Right, I wasn't aware of the Struct concept. So there's a first lesson ;)

> (*) Ruby allows for much shorter code, look e.g at
> def getCard
> if @cards.size == 0
> raise "No more cards in the deck"
> end
> return @cards.slice!(0)
> end
> which I would write as
> def getCard;
> @cards.shift or raise SomeNiceErrorClass, "No more cards in the deck"
> end

That's definitely shorter and more readable... I guess I'll learn to code this
way once I get to know the API better.

> (*) Personally I think it is nice to name CardSet#shuffle! with the
> "!". However more learned members of the community think that the
> existance of X#member! implies
> X#member and X#member is to be defined as
>
> def member; x = dup; x.member!; x end
>
> Just to let you know, I am with you but we are pretty alone ;)

Well, it is easy to just add this method if that is to be common Ruby style.

Yesterday I read part of Why's poignant guide to Ruby. I noticed that
:symbol's are used frequently.. is that also typical Ruby? IË?e. write

@someHash = { :foo => "bar" }

rather than

@someHash = { "foo" => "bar" }

is so, is (memory)efficiency the main reason?

Cheers

Bas

--
Bas van Gils <bas@van-gils.org>, http://www.va...
[[[ Thank you for not distributing my E-mail address ]]]

Quod est inferius est sicut quod est superius, et quod est superius est sicut
quod est inferius, ad perpetranda miracula rei unius.


Chad Perrin

6/12/2007 10:45:00 AM

0

On Tue, Jun 12, 2007 at 03:39:47AM +0900, Anthony Martinez wrote:
>
> From what I've been led to understand, method names consisting of
> multiple words should be named_with_underscores, not namedWithCamelcase.
>
> `puts' is the same as `print "something\n"'
>
> Parens can be omitted if it doesn't confuse the parser (or the reader)
>
> As well, reserve the { } form of blocks to one-liners.
>
> Taking these into account, instead of writing (from
> http://www.van-gils.org/~bas/bridgehan...):
>
> bg.suits.each{ |suit|
> cards = bg.north.cardsOfSuit(suit)
> print " #{bg.sortCards(cards)} \n"
> }
>
> write something like
>
> bg.suits.each do |suit|
> cards = bg.north.cards_of_suit suit
> puts " #{bg.sort_cards(cards)} "
> end
>
> Then again, these are highly subjective views, ones that I've absorbed
> from reading other people's ruby and getting into arguments with friends
> :) Take them with a grain of salt, as I'm not a Ruby expert and thus I
> might be wrong.

Your suggestions are pretty much canonical Ruby style, at first glance at
least.

--
CCD CopyWrite Chad Perrin [ http://ccd.ap... ]
Ben Franklin: "As we enjoy great Advantages from the Inventions of others
we should be glad of an Opportunity to serve others by any Invention of
ours, and this we should do freely and generously."

Chad Perrin

6/12/2007 10:50:00 AM

0

On Tue, Jun 12, 2007 at 03:33:32PM +0900, Bas van Gils wrote:
>
> Yesterday I read part of Why's poignant guide to Ruby. I noticed that
> :symbol's are used frequently.. is that also typical Ruby? I??e. write
>
> @someHash = { :foo => "bar" }
>
> rather than
>
> @someHash = { "foo" => "bar" }
>
> is so, is (memory)efficiency the main reason?

I believe it's a combination of efficiency and readability. The
differing syntax for a symbol as opposed to a string helps to provide an
immediate visual cue to the fact that it's a hash key, since that's by
far the most common place for symbols to be used (from what I've seen and
done). It's also one fewer character and two fewer keystrokes to type,
though I sincerely doubt that factors into most considerations. There
may be other reasons that apply, but that's what immediately occurs to
me.

--
CCD CopyWrite Chad Perrin [ http://ccd.ap... ]
W. Somerset Maugham: "The ability to quote is a serviceable substitute for
wit."

dblack

6/12/2007 10:59:00 AM

0

Rob Biedenharn

6/12/2007 2:26:00 PM

0

On Jun 12, 2007, at 6:59 AM, dblack@wobblini.net wrote:
> Hi --
>
> On Tue, 12 Jun 2007, Anthony Martinez wrote:
>
>> On Tue, Jun 12, 2007 at 03:10:49AM +0900, Bas van Gils wrote:
>
>> As well, reserve the { } form of blocks to one-liners.
>
> That's going to depend partly on whether you run across the
> (relatively rare) case where the precedence difference between {} and
> do/end actually matters. There are also some interesting ideas on
> record (see archives) involving blocks with side effects vs. blocks
> that just calculate. But I can't remember which is supposed to be
> which :-)
>
> <snip>
>
> David
>
> --
> * Books:
> RAILS ROUTING (new! http://safari.awprofessional.com/978...)
> RUBY FOR RAILS (http://www.manning...)
> * Ruby/Rails training
> & consulting: Ruby Power and Light, LLC (http://www.r...)

Jim Weirich tends to be an advocate of that convention: use do-end
for blocks that are "just blocks" and {} for blocks where the value
of the block is to be used. If you ever see any of Jim's code that
uses Builder, this convention is quite apparent. The problem of the
higher precedence of the braces can often be side-stepped by
parenthesizing the method arguments preceding the {block}. This is
one of the reasons that the do/end form is recommended for Rakefiles
so that the need for ()'s doesn't distract from the DSL-ish feel of
the task method.

I tend to merge this idea with the one for one-liners and prefer {}
in irb where the code isn't being saved anywhere and almost never use
{} in ERb templates where the opening and closing of the block are in
separate <% %>'s.

-Rob

Rob Biedenharn http://agileconsult...
Rob@AgileConsultingLLC.com



Robert Dober

6/12/2007 3:46:00 PM

0

> Almost. puts adds "\n" unless it's already there. So these are
> equivalent:
>
> print "hello\n"
> puts "hello\n"
Right but do you remember when I stupidly changed your code from
puts a
to
puts a.join("\n")

So this is another difference between print and puts, puts prints the
content of an array seperated by newlines. print does no such thing of
course.

> particular, please have mercy and don't leave the parens out in method
> signatures. Things like this:
>
> def a b, c, d = 1
>
> read very strangely, at least to my eyes.
I love it, I *really* read it better like this. But I guess the
community rather puts parens :( and if you want to comply listen to
David.
Let us just have a look at the Ruby core as David suggests below

All methods
ruby -e 'c=0;ARGF.each{|f|c+=1 if /^\s*def\s/===f};puts c' $(ruby -e
'puts Dir["**/*.rb"]')
18258
====
All methods with parens
ruby -e 'c=0;ARGF.each{|f|c+=1 if /^\s*def.*\(/===f};puts c' $(ruby
-e 'puts Dir["**/*.rb"]')
12271
====
All methods without parens and without parameters
ruby -e 'c=0;ARGF.each{|f|c+=1 if /^\s*def\s\w+\s*$/===f};puts c'
$(ruby -e 'puts Dir["**/*.rb"]')
5303 +
------
ruby -e 'c=0;ARGF.each{|f|c+=1 if /^\s*def\s\w+\s*#/===f};puts c'
$(ruby -e 'puts Dir["**/*.rb"]')
94 = 5397
--- ====
Leaves
ruby -e 'puts 18258 - 12271 - 5303 - 97'
587 methods corresponding to "our" style which makes
ruby -e 'puts 58700/18258.0'
3.21502902837112%

Not enough to get into parliament I'd say.



>
> > As well, reserve the { } form of blocks to one-liners.
>
> That's going to depend partly on whether you run across the
> (relatively rare) case where the precedence difference between {} and
> do/end actually matters. There are also some interesting ideas on
> record (see archives) involving blocks with side effects vs. blocks
> that just calculate. But I can't remember which is supposed to be
> which :-)
>
I try to avoid do end inside { }
Beware of this too
some_method a, b {|x| puts x}
will not work use either parens or do...end.

Cheers
Robert
--
You see things; and you say Why?
But I dream things that never were; and I say Why not?
-- George Bernard Shaw

dblack

6/12/2007 7:27:00 PM

0

Robert Dober

6/12/2007 7:49:00 PM

0

On 6/12/07, dblack@wobblini.net <dblack@wobblini.net> wrote:
> Hi --
>
> On Wed, 13 Jun 2007, Robert Dober wrote:
>
> >> Almost. puts adds "\n" unless it's already there. So these are
> >> equivalent:
> >>
> >> print "hello\n"
> >> puts "hello\n"
> > Right but do you remember when I stupidly changed your code from
> > puts a
> > to
> > puts a.join("\n")
> >
> > So this is another difference between print and puts, puts prints the
> > content of an array seperated by newlines. print does no such thing of
> > course.
> >
> >> particular, please have mercy and don't leave the parens out in method
> >> signatures. Things like this:
> >>
> >> def a b, c, d = 1
> >>
> >> read very strangely, at least to my eyes.
> > I love it, I *really* read it better like this. But I guess the
> > community rather puts parens :( and if you want to comply listen to
> > David.
> > Let us just have a look at the Ruby core as David suggests below
>
> Another little test:
>
> $ ruby -e 'puts
> ARGF.select{|f| f =~ /^\s*def\s\w+\s+\w+/}.size' $(ruby -e 'puts
> Dir["**/*.rb"]')
> 120
>
> $ ruby -e 'puts
> ARGF.select{|f| f =~ /^\s*def\s\w+\s+\w+/}.size' $(ruby -e 'puts
> Dir["**/*.rb"].reject {|fn| fn =~ /rexml/} ')
> 9
>
> :-) I think Sean is skewing the graph :-
I love that guy... ;)
Seriously it would be stupid to advice a newby into a personal style
that is way off mainstream and I did not.
But I will not put parens around my defs because I feel that if Ruby
gives me this possibility and I like it I should use it.

Now when it comes to working in teams the whole story changes again...
most important thing being a *consistent* style. By adopting a style
close to mainstream that can be achieved easier....

That is why I feel that this discussion is important.


>
> David
>
> --
> * Books:
> RAILS ROUTING (new! http://safari.awprofessional.com/978...)
> RUBY FOR RAILS (http://www.manning...)
> * Ruby/Rails training
> & consulting: Ruby Power and Light, LLC (http://www.r...)
>

Cheers
Robert
--
Books:
Wait a minute why is nobody publishing me ;)
Are you reading this Tim?

Robert