Any guides for good coding in Ruby?

A

Arfin

Is there some kind of class to format numbers? Something to let you
transform:

1 => "0001"
1234 => "1,234.00"

I needed to display the day and month in a 00 format and the way I did
it was adding a method to the Integer class

class Integer
def addZero
return "0" + self.to_s if self.to_s.length == 1
return self.to_s
end
end
t = Time.now
p "The date is: #{t.year}#{t.month.addZero}#{t.day.addZero}"

What do you guys think of this solution?


On a side note, could you guys give a few rules of thumb you follow in
order to make your code clean and readable?
 
J

James Edward Gray II

Is there some kind of class to format numbers? Something to let you
transform:

1 => "0001"
1234 => "1,234.00"

I'm not aware of a core Ruby tool for commiying numbers, but it's not
hard to roll a solution:

def commify( number )
        text = number.to_s.reverse
        text.gsub!(/(\d\d\d)(?=\d)(?!\ d*\.)/, '\1,')
        text.reverse
end
I needed to display the day and month in a 00 format and the way I did
it was adding a method to the Integer class

class Integer
def addZero
return "0" + self.to_s if self.to_s.length == 1
return self.to_s
end
end
t = Time.now
p "The date is: #{t.year}#{t.month.addZero}#{t.day.addZero}"

What do you guys think of this solution?

Kernel#sprintf and it's shortcut cousin String#% will handle this for
you. Here's an example:

"%02d" % 1 => "01"

Also look into Time#strftime for tasks like the above.
On a side note, could you guys give a few rules of thumb you follow in
order to make your code clean and readable?

Of course, there are loads of rules here and every person that gives
you a list will be different. Common sense ideas like, "Use good
variable names," apply in Ruby as they do everywhere else.

One of Ruby's great strengths is readability, I think. Play to your
strengths. Give the extra five keystrokes to make things utterly
clear, but don't be verbose if a concise line of code is obvious.

As always, common sense is needed.

James Edward Gray II
 
B

Bill Guindon

Is there some kind of class to format numbers? Something to let you
transform:

1 => "0001"
1234 => "1,234.00"

I needed to display the day and month in a 00 format and the way I did
it was adding a method to the Integer class

class Integer
def addZero
return "0" + self.to_s if self.to_s.length == 1
return self.to_s
end
end
t = Time.now
p "The date is: #{t.year}#{t.month.addZero}#{t.day.addZero}"

What do you guys think of this solution?

Might be easier with "printf" - although if you're not familiar with
it, might take a bit of work to get the format right.
On a side note, could you guys give a few rules of thumb you follow in
order to make your code clean and readable?

Some helpful stuff here:
http://www.caliban.org/ruby/rubyguide.shtml

Happy Rubying
 
F

Florian Gross

Arfin said:
Is there some kind of class to format numbers? Something to let you
transform:

1 => "0001"

"%04d" % 1

This is pretty much the same as sprintf() in C.

But in this case you can also do:

"1".rjust(4, "0")
1234 => "1,234.00"

I'd do that like this, even though there's other versions:

def number_format(number, padding_char = ",")
result = number.to_s
while pos = result.rindex(/\d{4}(?=\D|\Z)/)
result[pos + 1, 0] = padding_char
end
return result
end

irb(main):001:0> number_format 100_000_000
=> "100,000,000"
irb(main):002:0> number_format 10_000_000_000
=> "10,000,000,000"
irb(main):003:0> number_format "foo 10000000000 bar 50 qux 5000"
=> "foo 10,000,000,000 bar 50 qux 5,000"
 
M

Martin Ankerl

I try to follow the style that is predominant in the Ruby parts of the
Ruby source. Also, see:

I also do this, but there is one thing I cannot stand: every ruby lib
uses 2 spaces for indentation! IMHO it should be tabs, and *only* tabs.
This is much better, because in almost every editor it is possible to
set the tab width to whatever one likes. I hate 2 spaced sourcecode,
because I usually set one tab == 8 spaces, and use a non-fixed font.

martinus
 
P

Patrick Bennett

Martin said:
I also do this, but there is one thing I cannot stand: every ruby lib
uses 2 spaces for indentation! IMHO it should be tabs, and *only*
tabs. This is much better, because in almost every editor it is
possible to set the tab width to whatever one likes. I hate 2 spaced
sourcecode, because I usually set one tab == 8 spaces, and use a
non-fixed font.
I dislike 2 spaces as well, but tabs are worse. It's *extremely* and I
mean *extremely* rare for me to see a source file that uses tabs correctly.
Tabs can *never* be used for anything other than indenting the first
non-tab character on a line. That's it. As soon as they're used
anywhere else on a line following non-tab characters to 'line up' code,
then you've broken the ability for other users to use different tab
settings and view your code the same way. The *only* way of assuring a
consistent representation of source code is to use spaces and only
spaces for indentation and column alignment. Modern editors make using
spaces for tabs a non-issue anyway.

Patrick Bennett
 
J

James Edward Gray II

I also do this, but there is one thing I cannot stand: every ruby lib
uses 2 spaces for indentation! IMHO it should be tabs, and *only*
tabs. This is much better, because in almost every editor it is
possible to set the tab width to whatever one likes. I hate 2 spaced
sourcecode, because I usually set one tab == 8 spaces, and use a
non-fixed font.

Amen! I don't know who thought up the two space thing, but they were
out of line. :) In Ruby, you don't even need the extra characters to
keep lines short, generally. I'm set tabs to four spaces wide, but
it's definitely tabs all the way.

And while we're getting things off our chest, it really bugs me when
people don't keep their code within the 80 character boundary
guideline. I've been reading all the links posted in this thread and
they've all recommended it, but I can sure tell you from running Ruby
Quiz that not everyone is listening. ;)

James Edward Gray II
 
K

Kent Loobey

I don't know why the world doesn't code everything the way I do. It makes the
most sense to me!
 
J

Jim Freeze

Now that you guys have had a chance to air your feelings,
let's all get back to work, writing Ruby code with 2 spaces,
just as Matz does.

Oh, and by the way, it's four spaces if you are using Ruby C.

:)
 
B

Ben Giddings

Martin said:
I also do this, but there is one thing I cannot stand: every ruby lib
uses 2 spaces for indentation! IMHO it should be tabs, and *only* tabs.
This is much better, because in almost every editor it is possible to
set the tab width to whatever one likes. I hate 2 spaced sourcecode,
because I usually set one tab == 8 spaces, and use a non-fixed font.

Yay! Let's start a tabs vs. spaces flame war!!

My view? Tabs should never, ever be used in a file. (Ever) Can you
have a source code file without spaces? I doubt it. Can you have a
file without tabs? Certainly. Is mixing the two the main problem?
Yup. Use only spaces.

It's funny though. I think this eternal flame war is related to the
other eternal flame war: vi vs. emacs. In Emacs, the 'tab' button is
most often bound to 'indent-command'. This and 'indent-region' makes it
really easy to use spaces for indentation, and to adjust/fix someone
else's indentation when it's bad. On the other hand, I think vi makes
it much harder to use spaces for indentation, so tabs seem more attractive.

Anyhow, before throwing in your views, at least read up on other
people's arguments. :)

http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q="tabs vs spaces"

Ben
 
B

Bill Guindon

Now that you guys have had a chance to air your feelings,
let's all get back to work, writing Ruby code with 2 spaces,
just as Matz does.

Oh, and by the way, it's four spaces if you are using Ruby C.

Yes! 2 spaces is the way, the light, the shining path!
Death to all Tab heretics!

Just kidding (well, mostly anyway)
 
M

Martin Ankerl

Now that you guys have had a chance to air your feelings,
let's all get back to work, writing Ruby code with 2 spaces,
just as Matz does.

I feel much better now, and am now fit for some more years of 2-spaced
ruby code. :)

martinus
 
S

Sam Roberts

Quoting (e-mail address removed), on Wed, Mar 23, 2005 at 08:17:53AM +0900:
Yay! Let's start a tabs vs. spaces flame war!!

My view? Tabs should never, ever be used in a file. (Ever) Can you
have a source code file without spaces? I doubt it. Can you have a
file without tabs? Certainly. Is mixing the two the main problem?
Yup. Use only spaces.

It's funny though. I think this eternal flame war is related to the
other eternal flame war: vi vs. emacs. In Emacs, the 'tab' button is
most often bound to 'indent-command'. This and 'indent-region' makes it
really easy to use spaces for indentation, and to adjust/fix someone
else's indentation when it's bad. On the other hand, I think vi makes

Select the area, or whole file (%=), and press "=" in vim to do this. I
suspect = is standard on the ancient vi as well.
it much harder to use spaces for indentation, so tabs seem more attractive.

That's funny, I haven't found that emacs uses spaces to indent by
default. Its supposed to default to the GNU coding standard, though what
it does on any machine is pretty subject to the whims of who installed
it. The emacs standard/GNU indent style is the weirdest around, IMO.

foo()
{
int ;

if()
{
...

It uses TAB by default (every time indent gets over 8 chars, it uses a
TAB). I've always though the GNU coding style was specified to showcase
the power of the emacs indentation engine. I never got vim to do it, but
I just fed my functions through GNU indent, and whatever it looked like,
I comitted. Can't be acused of not following the GNU coding standards
then, GNU indents output is supposed to follow it!

I'm pretty easy about coding styles, everwhere I've worked has a
different one, the important thing is that people have the same one if
they work on their code a bunch. I do confess agreement with the 8th
commandment for C programmers:

Thou shalt make thy program's purpose and structure clear to thy
fellow man by using the One True Brace Style, even if thou likest it
not, for thy creativity is better used in solving problems than in
creating beautiful new impediments to understanding.

Particularly the last phrase abou where your creativity should be
focussed...

The only one style actually dislike is the GNU one. Also I think any
standard that I can't remember is way too detailed.

I'm averse to indents over about 4, and I think tabs are lame. They work
fine if everybody on your team uses the same settings, but when anybody
else looks at your code, it will look bad.

I think a bunch or ruby core developers (matz, for one) use emacs, so
many of the files use tabs, and indent two char widths per nesting
level. Not all, though.

Cheers,
Sam
 
J

James Edward Gray II


I just read this collection of very good tips. Thanks for the link!

One section does bother me there though:
Put methods where they belong

It's not a Ruby API design idiom, but anyway (perhaps we should split
this page in two: Ruby API idioms and design advices).

Classes are supposed to reflect reality. Thus, you should generally
put your methods where they belong, to reduce coupling. For example,
typical "data classes" should not have "actions", but methods to
access their data.

Example:
#
# Bad API
#
class GraphicElement
def draw(canvas)
raise "Implement me!"
end
end
class Circle < GraphicElement
def draw(canvas)
# Draw directly into the canvas
# (couples Circle with the canvas, as Circle
# follows this particular canvas API)
end
end

#
# Good API (definitely better than above, perhaps not the best)
#
class GraphicElement
def to_canvas(resolution)
raise "Implement me!"
end
end
class Circle < GraphicElement
def to_canvas(resolution)
# Convert circle to an array of arrays of pixels,
# taking into account the resolution parameter
end
end
class CanvasPainter
def paint(elmt, canvas, color=Color::BLACK,
centerX=0, centerY=0)
elmt.to_canvas.each do |x,y|
canvas.put(centerX+x, centerY+y, color)
end
end
end

I can't decide if it's just the example or the whole section, but this
one just doesn't feel right to me. I would much rather have a class
rendering itself (who better qualified?), then providing accessor like
data for others to do it. Push, don't pull, right?

An excellent book on this topic is Holub on Patterns, if you're
interested.

Anyway, just wanted to share. I really did love the page.

James Edward Gray II
 
E

Eric Schwartz

James Edward Gray II said:
I can't decide if it's just the example or the whole section, but this
one just doesn't feel right to me. I would much rather have a class
rendering itself (who better qualified?), then providing accessor like
data for others to do it. Push, don't pull, right?

If you have a class just providing data for others to render then you
can much more easily implement renderers than if you have to modify
your data class for each format you care to render it into.

-=Eric
 
B

Bill Guindon

Yay! Let's start a tabs vs. spaces flame war!!

My view? Tabs should never, ever be used in a file. (Ever) Can you
have a source code file without spaces? I doubt it. Can you have a
file without tabs? Certainly. Is mixing the two the main problem?
Yup. Use only spaces.

It's funny though. I think this eternal flame war is related to the
other eternal flame war: vi vs. emacs. In Emacs, the 'tab' button is
most often bound to 'indent-command'. This and 'indent-region' makes it
really easy to use spaces for indentation, and to adjust/fix someone
else's indentation when it's bad. On the other hand, I think vi makes
it much harder to use spaces for indentation, so tabs seem more attractive.

Anyhow, before throwing in your views, at least read up on other
people's arguments. :)

http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-8&q="tabs vs spaces"

Ok, I did (some) of the required reading, and found some of those
people are crazier than I am (which says a lot, but it's probably a
good thing).

My issue with tabs is mostly due to working on the web a lot, and
using admins that are composed of many textareas. AFAIK, there's not
a browser out there that lets you configure tab width in textareas,
and they all seem to default to the "traditional" 8 spaces.

btw, Mozilla 1.7.2 here, and if you know how to set that, I'll be
happy to hear it, but I'll continue to use my 2 spaces :)

Whatever you use (or come across in a file), shouldn't matter too
much, as most programmer's editors allow that to be changed fairly
easily.
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top