Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Ruby (http://www.velocityreviews.com/forums/f66-ruby.html)
-   -   a matter of style (http://www.velocityreviews.com/forums/t841470-a-matter-of-style.html)

Bas van Gils 06-11-2007 06:10 PM

a matter of style
 

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.van-gils.org/~bas/bridgehands/

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.van-gils.org
[[[ 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.



Anthony Martinez 06-11-2007 06:39 PM

Re: a matter of style
 
--a+b56+3nqLzpiR9O
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, Jun 12, 2007 at 03:10:49AM +0900, Bas van Gils wrote:
>=20
> All,
>=20
> 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 w=

hen
> 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 sma=

ll
> design and hacked up some unit tests. After a while no more tests failed:

[snip]=20
> 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* :-)
>=20
> Could anyone have a look at:
>=20
> http://www.van-gils.org/~bas/bridgehands/
>=20
> and give me some suggestions on style / ruby idiom / other things?
>=20
> Any help would be greatly appreciated,


=46rom 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/bridgehands/deal.rb):

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

write something like

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

Then again, these are highly subjective views, ones that I've absorbed
=66rom 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.

>=20
> yours=20
>=20
> Bas
>=20
> --=20
> Bas van Gils <bas@van-gils.org>, http://www.van-gils.org
> [[[ Thank you for not distributing my E-mail address ]]]
>=20
> Quod est inferius est sicut quod est superius, et quod est superius est s=

icut
> quod est inferius, ad perpetranda miracula rei unius.
>=20
>=20


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

--a+b56+3nqLzpiR9O
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)

iD8DBQFGbZbwKaiGM/xGKzQRArZ9AKCO/UYU4CIMl88wmMUB8XtdPiGppQCgxZgd
7Pt59vARuNASADT/+COx97E=
=3FIb
-----END PGP SIGNATURE-----

--a+b56+3nqLzpiR9O--


Robert Dober 06-11-2007 06:58 PM

Re: a matter of style
 
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.van-gils.org/~bas/bridgehands/


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.van-gils.org
> [[[ 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 06-12-2007 06:33 AM

Re: a matter of style
 

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.van-gils.org
[[[ 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 06-12-2007 10:45 AM

Re: a matter of style
 
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/bridgehands/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.


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

--
CCD CopyWrite Chad Perrin [ http://ccd.apotheon.org ]
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 06-12-2007 10:50 AM

Re: a matter of style
 
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.apotheon.org ]
W. Somerset Maugham: "The ability to quote is a serviceable substitute for
wit."


dblack@wobblini.net 06-12-2007 10:59 AM

Re: a matter of style
 
Hi --

On Tue, 12 Jun 2007, Anthony Martinez wrote:

> 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.van-gils.org/~bas/bridgehands/
>>
>> 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"'


Almost. puts adds "\n" unless it's already there. So these are
equivalent:

print "hello\n"
puts "hello\n"

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


Can be, but it's best not to get too cutesy with it :-) In
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.

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

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


Reading Ruby code, in particular the Ruby source code itself, is a
great way to see the traditional style. I've never seen anyone
improve on that style. People get very excited about the fact that
Ruby lets you "do your own thing" in terms of style -- like:

printf( "My name is %s\n", thisPerson.name() );

and such... but if most Ruby were written like that I think I would
have put the Pickaxe back on the shelf at the bookstore :-)


David

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


Rob Biedenharn 06-12-2007 02:26 PM

Re: a matter of style
 
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/9780321509246)
> RUBY FOR RAILS (http://www.manning.com/black)
> * Ruby/Rails training
> & consulting: Ruby Power and Light, LLC (http://www.rubypal.com)


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://agileconsultingllc.com
Rob@AgileConsultingLLC.com




Robert Dober 06-12-2007 03:46 PM

Re: a matter of style
 
> 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@wobblini.net 06-12-2007 07:26 PM

Re: a matter of style
 
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 :-


David

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



All times are GMT. The time now is 01:54 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.