WebProgrammingTalk Web Programming Ruby on Rails
Dangerous Ruby Hello There, Guest! (LoginRegister)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dangerous Ruby
09-27-2010, 08:48 AM, (This post was last modified: 09-27-2010, 08:53 AM by sphere.)
Dangerous Ruby
Ruby makes it easy to create a lot of functional code in a short period of time. However, there are some instances where you must be explicit and take care to avoid errors.

Local Variables versus Methods

If a local variable exists with the same name as a method, the local variable will be used unless you put parentheses behind the method or use self.methodName.

def colors(arg1="blue", arg2="red")
    "#{arg1}, #{arg2}"

colors = 6
print colors

The above outputs 6. If you were expecting to use the color method, you might have been surprised. Using parentheses, in this case, would yield the desired result:

def colors(arg1="blue", arg2="red")
    "#{arg1}, #{arg2}"

colors = 6

print colors("purple", "chartreuse")

This outputs:

purple, chartreuse

More Whitespace Issues

You need to ensure that you use whitespace properly when using methods, as extra whitespace can result in errors.

def countdownLength= length
def countdownLength=(length)
def countdownLength= (length)
def countdownLength= ( length )

The above works fine, while this:

def countdownLength = (length)

results in a parse error, because the whitespace before the equal sign makes it part of the method name.

Block Local Variables

Be careful to keep variables in the scope for which they are intended. Not doing so will yield in unexpected results. Here’s a particularly nasty one:

i = 0
while i < 10
    [1,2,3].each {|i| ... } # i gets overwritten here
    i += 1

While we intended the i within the each iterator to stay in its own scope, it actually overwrote the i in the while loop, resulting in an endless loop.
10-25-2010, 11:15 AM,
Re: Dangerous Ruby
Oh yeah, i can see that in the coding. I find this useful 'cause this can happen with other programming.
12-04-2010, 12:05 AM,
Re: Dangerous Ruby
Great article thanks for sharing Smile

Forum Jump:

Users browsing this thread: 1 Guest(s)
Contact Us | WebProgrammingTalk | Return to Top | | Lite (Archive) Mode | RSS Syndication