Web Programming Talk

Please login or register.

Login with username, password and session length
Advanced search  

News:

Free Web Hosting Package for You! Click here for more infomation.

Author Topic: Dangerous Ruby  (Read 556 times)

sphere

  • Guest
Dangerous Ruby
« on: September 27, 2010, 08:48:37 AM »

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}"
end


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}"
end

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
end


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.
  
« Last Edit: September 27, 2010, 08:53:46 AM by Sphere »
Logged

Nikorasu

  • Full Member
  • ***
  • Reputation: 0
  • Posts: 100
    • View Profile
Re: Dangerous Ruby
« Reply #1 on: October 25, 2010, 11:15:40 AM »

Oh yeah, i can see that in the coding. I find this useful 'cause this can happen with other programming.
Logged

Shole

  • Full Member
  • ***
  • Reputation: 0
  • Posts: 115
    • View Profile
    • IHost4You
Re: Dangerous Ruby
« Reply #2 on: December 04, 2010, 12:05:55 AM »

Great article thanks for sharing :)
Logged
Ihost4you.com
 

anything