变量和定义变量

为了把数值或字符串保存在内存中供后面程序使用,需要给他们命名。
程序员把这个过程叫定义变量,定义的名称叫变量。
只有当解释器看到有变量定义后,这个变量才会产生,也就是说,不会给变量预先分配地址和空间。
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”是方法的调用者。
“.”前面的对象和后面的方法是调用和被调用的关系。

转载于:https://www.cnblogs.com/lipton/archive/2011/05/07/2040029.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值