Tuesday, July 31, 2012

Basic Ruby Syntax


def say_goodnight(name)
result = "Good night, " + name
return result
end

# Time for bed...
puts say_goodnight("jim")
puts say_goodnight("mary")
puts "And good night,\nGrandma."

# ...and a different way to rewrite the above def
def gnight(name)
result = "Good night, #{name}"
return result
end

puts gnight('Pa')

#...and another way
def good_night(name)
result = "Good night, #{name.capitalize}"
return result
end
puts good_night('uncle')

#...and a shorter way
def goodnight(name)
"Good night, #{name.capitalize}"
end
puts goodnight('ma')
# The value returned by a ruby method is the value of the last
# expression evaluated, so we can get rid of the temporary
# variable and the return statement altogether.
# This is idiomatic ruby.


Source: Programming Ruby

No comments:

Post a Comment