def say_goodnight(name)
result = "Good night, " + name
return result
end
# Time for bed
puts say_goodnight("John-Boy")
puts say_goodnight("Mary-Ellen")
As the example shows, Ruby syntax is clean: (1) don't need semicolons at the ends of statements as long as you put each statement on a sepatate line. (2) Ruby comments start with # character and run to the end of the line. (3) indentation is not sighificant (but using two-character indentation will make you friends in the community if you plan on distributing your code)
Methods are defined with the keyword def , followed by the method name(in this case, say_goodnight) and the method's parameters between parentheses, and finished the body with the keyword end. Note that we didn't have to declare the variable result: it sprang into existence when we assigned to it.
Ruby string objects: we have many ways to create a string object, but propbably the most commom is to use string literals: sequences of characters between single or double quotation marks. The difference between the two forms is the amount of processing Ruby does on the string while constructing the literal. In the single-quoted case, Ruby does very little. With a few exceptions, what you type into the string literal becomes the string's value.In the double-quoted case, Ruby does more work:
(1) puts "and good night, \nGrandma" --> and good night, 换行 Grandma
(2) def say_goodnight(name)
result = "Good night,#{name}"
return result
end
# Time for bed
puts say_goodnight('John-Boy')
puts say_goodnight("Mary-Ellen")
(3)def say_goodnight(name)
result = "Good night,#{name.capitalize}" 还可以调用些方法
return result
end
# Time for bed
puts say_goodnight('john-Boy')
puts say_goodnight("mary-Ellen")
(4) def say_goodnight(name)
"Good night,#{name.capitalize}" 可以不定义变量
end
# Time for bed
puts say_goodnight('john-Boy')
puts say_goodnight("mary-Ellen")
结果均为:Good night,John-boy
Good night,Mary-ellen
评论