Things That Newcomers to Ruby Should Know

Things That Newcomers to Ruby Should Know

···

=========================================

  1. Resources:

HOME PAGE: http://www.ruby-lang.org/en/
FAQ : http://www.rubycentral.com/faq/
PITFALL : http://rwiki.jin.gr.jp/cgi-bin/rw-cgi.rb?cmd=view;name=pitfall
ONLINE TUTORIAL/DOC/BOOK: http://www.rubycentral.com/book/

  1. Use “ruby -w” instead of simply “ruby” to get helpful warnings. If not
    invoking “ruby” directly, we can use instead:

win32:
C:> set RUBYOPT=w
or
pressing F5 (to execute script) in the Scite editor will give you warnings
(and F4 will position at problematic line).

unix:
sh# export RUBYOPT="w"
or
csh# setenv RUBYOPT “w”

  1. The String#[Fixnum] method does not return the “character” (which is a
    string of length one) at the Fixnum position, but instead the character
    code at the position (however, this may change in the future). Currently,
    to get the character, use String#[Fixnum,1] instead.

  2. Be aware of the lexical scoping interaction between local variables and
    block local variables. If a local variable is already defined before the
    block, then the block will use (and quite possibly) modify the local
    variable; in this case the block does not introduce a new scope.

  3. In Ruby, there are two sets of logical operators: [!, &&, ||] and [not,
    and, or]. [!, &&, ||]'s precedence is higher than the assignments (=, %=,
    ~=, /=, etc.) while [not, and, or]'s precedence is lower. Also note that
    while &&'s precedence is higher than ||'s, the and’s precedence is the
    same as the or’s.

  4. In the case statement

    case obj
    when obj1

it is the “===” method which is invoked, not the “==” method. Also, the
order is “obj1 === obj” and not “obj === obj1”.

  1. Array.new(2, Hash.new) returns an array with two elements referencing
    the same, indentical hash, and not two independent hashes.

  2. After reading data from a file and putting them into variables, the
    data type is really String. To convert them into numbers, use the
    "to_i" or “to_f” methods. If you use the “+” operator to add the
    "numbers" without calling the conversion methods, for example, you will
    simply concatenate the strings.

An alternative is to use “scanf” (http://www.rubyhacker.com/code/scanf).

  1. It is advisable not to write some white space before the opening ‘(’ in
    a method call; else, Ruby with $VERBOSE set to true may give you a
    warning.

  2. The “dot” for method call is the strongest operator. So for example,
    while in some other languages the number after the dot in a floating point
    number is optional, it is not in Ruby. For example, 1.e6 will try to call
    the method “e6” of the object 1 (which is a Fixnum). You have to write
    1.0e6.

However, notice that although the dot is the strongest operator, its
precedence with respect to method name may be different with different
Ruby versions. At least in Ruby 1.6.7, “puts (1…3).length” will give you
a syntax error; you should write “puts((1…3).length)” instead.

  1. The notation “Class#method” in a documentation is used only to
    represent an instance method of an object of class Class. It is not a
    Ruby syntax at all. A class method in a documentation, on the other hand,
    is usually represented as “Class.method” (which is a valid Ruby syntax).

Hi,

Because of my own “gotcha!” wrt Hash#rehash, I just updated the list by
adding more resources in item 0) and my own gotcha as item 11).

Regards,

Bill

Things That Newcomers to Ruby Should Know

···

=========================================

  1. Resources:

HOME PAGE : http://www.ruby-lang.org/en/
FAQ : http://www.rubycentral.com/faq/
PITFALL : http://rwiki.jin.gr.jp/cgi-bin/rw-cgi.rb?cmd=view;name=pitfall
ONLINE TUTORIAL/DOC/BOOK: http://www.rubycentral.com/book/
VERY USEFUL HINTS :

  • “Programming Ruby” book by David Thomas and Andrew Hunt, “When Trouble
    Strikes” Chapter, “But It Doesn’t Work” Section.
  • “The Ruby Way” by Hal Fulton, Chapter 1: “Ruby In Review”
  1. Use “ruby -w” instead of simply “ruby” to get helpful warnings. If not
    invoking “ruby” directly, we can use instead:

win32:
C:> set RUBYOPT=w
or
pressing F5 (to execute script) in the Scite editor will give you warnings
(and F4 will position at problematic line).

unix:
sh# export RUBYOPT="w"
or
csh# setenv RUBYOPT “w”

  1. The String#[Fixnum] method does not return the “character” (which is a
    string of length one) at the Fixnum position, but instead the character
    code at the position (however, this may change in the future). Currently,
    to get the character, use String#[Fixnum,1] instead.

  2. Be aware of the lexical scoping interaction between local variables and
    block local variables. If a local variable is already defined before the
    block, then the block will use (and quite possibly) modify the local
    variable; in this case the block does not introduce a new scope.

  3. In Ruby, there are two sets of logical operators: [!, &&, ||] and [not,
    and, or]. [!, &&, ||]'s precedence is higher than the assignments (=, %=,
    ~=, /=, etc.) while [not, and, or]'s precedence is lower. Also note that
    while &&'s precedence is higher than ||'s, the and’s precedence is the
    same as the or’s.

  4. In the case statement

    case obj
    when obj1

it is the “===” method which is invoked, not the “==” method. Also, the
order is “obj1 === obj” and not “obj === obj1”.

  1. Array.new(2, Hash.new) returns an array with two elements referencing
    the same, indentical hash, and not two independent hashes.

  2. After reading data from a file and putting them into variables, the
    data type is really String. To convert them into numbers, use the
    "to_i" or “to_f” methods. If you use the “+” operator to add the
    "numbers" without calling the conversion methods, for example, you will
    simply concatenate the strings.

An alternative is to use “scanf” (http://www.rubyhacker.com/code/scanf).

  1. It is advisable not to write some white space before the opening ‘(’ in
    a method call; else, Ruby with $VERBOSE set to true may give you a
    warning.

  2. The “dot” for method call is the strongest operator. So for example,
    while in some other languages the number after the dot in a floating point
    number is optional, it is not in Ruby. For example, 1.e6 will try to call
    the method “e6” of the object 1 (which is a Fixnum). You have to write
    1.0e6.

However, notice that although the dot is the strongest operator, its
precedence with respect to method name may be different with different
Ruby versions. At least in Ruby 1.6.7, “puts (1…3).length” will give you
a syntax error; you should write “puts((1…3).length)” instead.

  1. The notation “Class#method” in a documentation is used only to
    represent an instance method of an object of class Class. It is not a
    Ruby syntax at all. A class method in a documentation, on the other hand,
    is usually represented as “Class.method” (which is a valid Ruby syntax).

  2. Be careful when using “mutable” objects as hash keys. To get the
    expected result, call Hash#rehash before accessing the hash
    elements. Example:

s = "mutable"
arr = [s]
hash = { arr => “object” }
s.upcase!
p hash[arr] # >> nil (maybe not what was expected)
hash.rehash
p hash[arr] # >> “object”

  1. For comments, please e-mail me directly at billtj@glue.umd.edu.

Good work, Bill. This should be posted here once a month, like a FAQ. My
comments are interleaved below. All are strictly IMO.

Things That Newcomers to Ruby Should Know

  1. Resources:

HOME PAGE: Ruby Programming Language
FAQ : http://www.rubycentral.com/faq/
PITFALL : http://rwiki.jin.gr.jp/cgi-bin/rw-cgi.rb?cmd=view;name=pitfall
ONLINE TUTORIAL/DOC/BOOK: http://www.rubycentral.com/book/

  1. Use “ruby -w” instead of simply “ruby” to get helpful warnings. If not
    invoking “ruby” directly, we can use instead:

win32:
C:> set RUBYOPT=w
or
pressing F5 (to execute script) in the Scite editor will give you warnings
(and F4 will position at problematic line).

unix:
sh# export RUBYOPT=“w”
or
csh# setenv RUBYOPT “w”

This could be briefer: “set environment variable RUBYOPT to ‘w’”. The ability
to set environment variables can be assumed in this community.

  1. The String#[Fixnum] method does not return the “character” (which is a
    string of length one) at the Fixnum position, but instead the character
    code at the position (however, this may change in the future). Currently,
    to get the character, use String#[Fixnum,1] instead.

It is useful for newbies to know about #chr, #ord and ?x syntax as well.

  1. Be aware of the lexical scoping interaction between local variables and
    block local variables. If a local variable is already defined before the
    block, then the block will use (and quite possibly) modify the local
    variable; in this case the block does not introduce a new scope.

  2. In Ruby, there are two sets of logical operators: [!, &&, ||] and [not,
    and, or]. [!, &&, ||]'s precedence is higher than the assignments (=, %=,
    ~=, /=, etc.) while [not, and, or]'s precedence is lower. Also note that
    while &&'s precedence is higher than ||'s, the and’s precedence is the
    same as the or’s.

  3. In the case statement

    case obj
    when obj1

it is the “===” method which is invoked, not the “==” method. Also, the
order is “obj1 === obj” and not “obj === obj1”.

An example of usage would bde really good here. There are three interesting
cases: classes, regexen and ranges.

  1. Array.new(2, Hash.new) returns an array with two elements referencing
    the same, indentical hash, and not two independent hashes.

Would read better as
Array.new(2, {}) → [{}, {}]
but the array elements are identical objects, not independent hashes.

  1. After reading data from a file and putting them into variables, the
    data type is really String. To convert them into numbers, use the
    “to_i” or “to_f” methods. If you use the “+” operator to add the
    “numbers” without calling the conversion methods, for example, you will
    simply concatenate the strings.

An alternative is to use “scanf” (scanf for Ruby, v.1.1.1).

  1. It is advisable not to write some white space before the opening ‘(’ in
    a method call; else, Ruby with $VERBOSE set to true may give you a
    warning.

  2. The “dot” for method call is the strongest operator. So for example,
    while in some other languages the number after the dot in a floating point
    number is optional, it is not in Ruby. For example, 1.e6 will try to call
    the method “e6” of the object 1 (which is a Fixnum). You have to write
    1.0e6.

However, notice that although the dot is the strongest operator, its
precedence with respect to method name may be different with different
Ruby versions. At least in Ruby 1.6.7, “puts (1…3).length” will give you
a syntax error; you should write “puts((1…3).length)” instead.

  1. The notation “Class#method” in a documentation is used only to
    represent an instance method of an object of class Class. It is not a
    Ruby syntax at all. A class method in a documentation, on the other hand,
    is usually represented as “Class.method” (which is a valid Ruby syntax).

s/in a documentation/(in documentation|in a document)/g

I think the whole paragraph would read better as:
The notation Class#method (or just #method) is an unofficial way to talk
about methods which is widely used in the Ruby community. In Ruby syntax
and proper documentation, the notation “Class.method” is used.


  1. Many more introductory pitfalls, as well as advice for Perl and Python
    programmers, are included in “The Ruby Way” (see “Resources”).

Gavin

···

From: “William Djaja Tjokroaminata” billtj@z.glue.umd.edu

Well, these were the things I should have known:

  • the “?” before a char returns its value
  • 0 is actually true
  • the ||= operator exists :slight_smile:
···

On Mon, 30 Sep 2002 14:59:56 +0000 (UTC), William Djaja Tjokroaminata billtj@z.glue.umd.edu wrote:

Things That Newcomers to Ruby Should Know

Hi,

Because of a request, I have quickly put the list (in plain text
format) on a web page: “http://www.glue.umd.edu/~billtj/ruby.html”. When
I have time, I will try to convert it to better HTML format…

Regards,

Bill

“Gavin Sinclair” gsinclair@soyabean.com.au wrote in message
news:01ec01c268df$45b59900$526332d2@nosedog…

Good work, Bill. This should be posted here once a month, like a FAQ.

It should be a FAP: Frequently Applied Pitfalls.

Mikkel

Thanks a lot, Gavin; I will try to incorporate your input. I will also
try to put it in rubygarden (I never put an input to rubygarden before, so
I was rather puzzed… :slight_smile: )

Regards,

Bill

···

============================================================================
Gavin Sinclair gsinclair@soyabean.com.au wrote:

Good work, Bill. This should be posted here once a month, like a FAQ. My
comments are interleaved below. All are strictly IMO.
(deleted)

Thanks, Gabriele. I will try to incorporate your input. The “0 is
actually true” is particularly a valid concern, for people coming from
other languages such as C and Perl.

Regards,

Bill

···

==========================================================================
gabriele renzi <surrender_it@ yahoo.it> wrote:

Well, these were the things I should have known:

  • the “?” before a char returns its value
  • 0 is actually true
  • the ||= operator exists :slight_smile:

I’ve copied it to the Wiki, for I do really think it’ll save you time :wink:

···

On Tue, Oct 01, 2002 at 06:18:15AM +0900, William Djaja Tjokroaminata wrote:

Hi,

Because of a request, I have quickly put the list (in plain text
format) on a web page: “http://www.glue.umd.edu/~billtj/ruby.html”. When
I have time, I will try to convert it to better HTML format…

Regards,

Bill


_ _

__ __ | | ___ _ __ ___ __ _ _ __
'_ \ / | __/ __| '_ _ \ / ` | ’ \
) | (| | |
__ \ | | | | | (| | | | |
.__/ _,
|_|/| || ||_,|| |_|
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

Linux - Das System fuer schlaue Maedchen :wink:
– banshee

Hi,

Because of a request, I have quickly put the list (in plain text
format) on a web page: “http://www.glue.umd.edu/~billtj/ruby.html”. When
I have time, I will try to convert it to better HTML format…

How about a page on the RubyGarden Wiki ?

MikkelFJ wrote:

It should be a FAP: Frequently Applied Pitfalls.

Applied?

Then: “Let us just apply design pattern XYZ.”
Now: “Let us just apply design pitfall ZYX.”

There is such a thing as being too honest :slight_smile:

···


([ Kent Dahl ]/)_ ~ [ http://www.stud.ntnu.no/~kentda/ ]/~
))_student
/(( _d L b_/ NTNU - graduate engineering - 5. year )
( __õ|õ// ) )Industrial economics and technological management(
_
/ö____/ (_engineering.discipline=Computer::Technology)

I believe you didn’t receive my previous message.
I have already copied it to the Wiki, under

···

On Tue, Oct 01, 2002 at 10:38:51AM +0900, William Djaja Tjokroaminata wrote:

Thanks a lot, Gavin; I will try to incorporate your input. I will also
try to put it in rubygarden (I never put an input to rubygarden before, so
I was rather puzzed… :slight_smile: )


_ _

__ __ | | ___ _ __ ___ __ _ _ __
'_ \ / | __/ __| '_ _ \ / ` | ’ \
) | (| | |
__ \ | | | | | (| | | | |
.__/ _,
|_|/| || ||_,|| |_|
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

All the existing 2.0.x kernels are to buggy for 2.1.x to be the
main goal.
– Alan Cox

  • the ||= operator exists :slight_smile:
    But not for class variables…

±[Kontra, Gergely @ Budapest University of Technology and Economics]-+

    Email: kgergely@mcl.hu,  kgergely@turul.eet.bme.hu          |

URL: turul.eet.bme.hu/~kgergely Mobile: (+36 20) 356 9656 |
±------“Olyan langesz vagyok, hogy poroltoval kellene jarnom!”-------+
.
Magyar php mirror es magyar php dokumentacio: http://hu.php.net

Hi Mauricio (or Batsman? :slight_smile: ),

I did and I checked it. But I was puzzed by:

  • Who have the write access to the web page?
  • How to commit a change?
  • etc.

The reason is that I think the list will continue to change for a while
(hopefully not forever, or at least only asymptotically), including the
format and the ordering.

Regards,

Bill

···

===========================================================================
Mauricio Fern?ndez batsman.geo@yahoo.com wrote:

I believe you didn’t receive my previous message.
I have already copied it to the Wiki, under
http://www.rubygarden.org/ruby?ThingsNewcomersShouldKnow

Hi,

I am sorry that I don’t understand what you meant. I am using ruby 1.6.7
(2002-03-01) [i686-linux]:

-------------------------------------------

class MyClass
def initialize
data = false
data ||= true
puts data # >> true
@data = false
@data ||= true
puts @data # >> true
@@data = false
@@data ||= true
puts @@data # >> true
end
end
MyClass.new

-------------------------------------------

It seems that the ||= operator works for local, instance, and class
variables.

Regards,

Bill

···

===========================================================================
Kontra, Gergely kgergely@mlabdial.hit.bme.hu wrote:

  • the ||= operator exists :slight_smile:
    But not for class variables…

Hi Mauricio (or Batsman? :slight_smile: ),

batsman is my nickname (don’t ask where it comes from; it is ~8 years
old now)
BTW, it feels strange to see it capitalized :slight_smile: kinda like “matz”

I did and I checked it. But I was puzzed by:

  • Who have the write access to the web page?

Everybody.
If you want your name to be in the modifications summary, you can
register yourself.

  • How to commit a change?

Simply follow the “Edit Text of This Page” link at the bottom. You can
edit the page right from the browser, ie there’s no need to upload it
with FTP.

  • etc.

You might want to read an introduction to Wikis in

As for the formatting rules, they’re available at

The reason is that I think the list will continue to change for a while
(hopefully not forever, or at least only asymptotically), including the
format and the ordering.

The Wiki is a very dynamic tool. The Wiki node can evolve as fast as
needed, as you’re only a link away from editing it…

···

On Thu, Oct 03, 2002 at 07:04:03AM +0900, William Djaja Tjokroaminata wrote:


_ _

__ __ | | ___ _ __ ___ __ _ _ __
'_ \ / | __/ __| '_ _ \ / ` | ’ \
) | (| | |
__ \ | | | | | (| | | | |
.__/ _,
|_|/| || ||_,|| |_|
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

Linux is addictive, I’m hooked!
– MaDsen Wikholm’s .sig

Hi –

  • the ||= operator exists :slight_smile:
    But not for class variables…

Hi,

I am sorry that I don’t understand what you meant. I am using ruby 1.6.7
(2002-03-01) [i686-linux]:

-------------------------------------------

class MyClass
def initialize
data = false
data ||= true
puts data # >> true
@data = false
@data ||= true
puts @data # >> true
@@data = false
@@data ||= true
puts @@data # >> true
end
end
MyClass.new

-------------------------------------------

It seems that the ||= operator works for local, instance, and class
variables.

Yes, if the class var is already initialized. However (1.6.7):

candle:~$ ruby -ve ‘a ||= 3; @a ||= 3; @@a ||= 3’
ruby 1.6.7 (2002-03-01) [i686-linux]
-e:1: uninitialized class variable @@a in Object (NameError)

I seem to be between 1.7 installations, so I can’t test it… but I
believe that’s what Gergely meant.

David

···

On Fri, 11 Oct 2002, William Djaja Tjokroaminata wrote:

Kontra, Gergely kgergely@mlabdial.hit.bme.hu wrote:


David Alan Black | Register for RubyConf 2002!
home: dblack@candle.superlink.net | November 1-3
work: blackdav@shu.edu | Seattle, WA, USA
Web: http://pirate.shu.edu/~blackdav | http://www.rubyconf.com

William Djaja Tjokroaminata wrote:

I am sorry that I don’t understand what you meant. I am using ruby 1.6.7
(2002-03-01) [i686-linux]:

-------------------------------------------

class MyClass
def initialize
data = false

Comment out the above line, and all is well.

            data ||= true
            puts data       # >> true
            @data = false

Comment out the above line, and all is still well.

            @data ||= true
            puts @data      # >> true
            @@data = false

Comment out the above line, and you get:
in `initialize’: uninitialized class variable @@data in MyClass
(NameError)

            @@data ||= true
            puts @@data     # >> true
    end

end
MyClass.new

-------------------------------------------

It seems that the ||= operator works for local, instance, and class
variables.

For class variables, only when the class variable is already defined.

···


([ Kent Dahl ]/)_ ~ [ http://www.stud.ntnu.no/~kentda/ ]/~
))_student
/(( _d L b_/ NTNU - graduate engineering - 5. year )
( __õ|õ// ) )Industrial economics and technological management(
_
/ö____/ (_engineering.discipline=Computer::Technology)

Hi,

This is very interesting. Should Ruby be more consistent in this respect?

Regards,

Bill

···

=========================================================================
dblack@candle.superlink.net wrote:

On Fri, 11 Oct 2002, William Djaja Tjokroaminata wrote:

It seems that the ||= operator works for local, instance, and class
variables.

Yes, if the class var is already initialized. However (1.6.7):

candle:~$ ruby -ve ‘a ||= 3; @a ||= 3; @@a ||= 3’
ruby 1.6.7 (2002-03-01) [i686-linux]
-e:1: uninitialized class variable @@a in Object (NameError)

William Djaja Tjokroaminata wrote:

Yes, if the class var is already initialized. However (1.6.7):

candle:~$ ruby -ve ‘a ||= 3; @a ||= 3; @@a ||= 3’
ruby 1.6.7 (2002-03-01) [i686-linux]

This is very interesting. Should Ruby be more consistent in this respect?

That might be a bad idea, since class variables are more “magical” than
both instance variables and local variables.

The inheritance hierarchy level where the class variable is first
defined decides where it is visible. This is not a problem with local
variables nor instance variables. Although it is alot more verbose,
using the “@@a = 1 unless defined? @@a” trick gives you the same
functionality, but is easier to spot while reading, if it causes a bug.

···

dblack@candle.superlink.net wrote:


([ Kent Dahl ]/)_ ~ [ http://www.stud.ntnu.no/~kentda/ ]/~
))_student
/(( _d L b_/ NTNU - graduate engineering - 5. year )
( __õ|õ// ) )Industrial economics and technological management(
_
/ö____/ (_engineering.discipline=Computer::Technology)