变量和定义变量

为了把数值或字符串保存在内存中供后面程序使用,需要给他们命名。
程序员把这个过程叫定义变量,定义的名称叫变量。
只有当解释器看到有变量定义后,这个变量才会产生,也就是说,不会给变量预先分配地址和空间。
s = 'Hello World!'
x = 10
# p004stringusage.rb
# Defining a constant
PI = 3.1416
puts PI
# Defining a local variable
myString = 'I love my city, Pune'
puts myString
=begin
Conversions
.to_i, .to_f, .to_s
=end
var1 = 5;
var2 = '2'
puts var1 + var2.to_i
# << appending to a string
a = 'hello '
a<<'world.
I love this world...'
puts a
=begin
<< marks the start of the string literal and
is followed by a delimiter of your choice.
The string literal then starts from the next
new line and finishes when the delimiter is
repeated again on a line on its own.
=end
a = <<END_STR
This is the string
And a second line
END_STR
puts a
变量的命名有一定规则:以小写字母或下划线开头,变量中只能包含字母,数字和下划线。关键字不能作为变量名使用。
当ruby解释器读到一个单词的时候,他会把他解释成变量名,方法名或者保留关键字中的一种。
如果单词的后面跟一个“=”,说明是一个变量;如果是一个关键字,那就只能作为关键字使用;其他情况视为方法名。
在下面的例子中:
x = "100".to_i
“.”的意思是方法to_i被字符串“100”调用。
字符串“100”是方法的调用者。
“.”前面的对象和后面的方法是调用和被调用的关系。
posted @ 2011-05-07 21:32  Lipton  阅读(694)  评论(0编辑  收藏  举报