Tuesday, July 31, 2012

Create array using %w



Use %w as a shortcut to make an array. For example...

a = %w{ ant bee cat dog elk } will give you...

a = [ 'ant', 'bee', 'cat', 'dog', 'elk' ]

To test (inside irb),
a[0]
=> "ant"

a[3]
=> "dog"

Source - Programming Ruby

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

Friday, July 27, 2012

#{ something }

number = 5
"The number is #{number}."
"The number is #{5}."
"The number after #{number} is #{number.next}."
"The number prior to #{number} is #{number-1}."
"We're ##{number}!"

#{ number } will get whatever you assign to the variable number.

"...Any text kept within the brackets of the special marker #{} (that is, #{text in here}) is interpreted as a Ruby expression. The result of that expression is substituted into the string that gets created. If the result of the expression is not a string, Ruby calls its to_s method and uses that instead."

(Source -- Ruby Cookbook)