正文

Some Basic Ruby2007-03-12 15:25:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/daweizhao/23871.html

分享到:

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


 

阅读(1744) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册