Ruby - 变量声明

Ruby - 变量声明 首页 / Ruby入门教程 / Ruby - 变量声明

变量是存储位置,用于保存任何程序要使用的任何数据,Ruby支持五种类型的变量,本章介绍了这五种变量。

Ruby 全局变量

全局变量以 "$" 开头。未初始化的全局变量的值为nil并使用-w选项生成警告。

分配给全局变量会更改全局状态,不建议使用全局变量,它们使程序变得很难维护,下面是全局变量示例。

#!/usr/bin/ruby

$global_variable=10
class Class1
   def print_global
      puts "Global variable in Class1 is #$global_variable"
   end
end
class Class2
   def print_global
      puts "Global variable in Class2 is #$global_variable"
   end
end

class1obj=Class1.new
class1obj.print_global
class2obj=Class2.new
class2obj.print_global

$global_variable是全局变量。这将产生以下输出-

注意-在Ruby中,您可以通过在变量或常量之前放置一个井号(#)来访问任何变量或常量的值。

Global variable in Class1 is 10
Global variable in Class2 is 10

Ruby 变量

变量以@开头。未初始化的变量的值为nil并使用-w选项生成警告。

这是显示变量用法的示例。

#!/usr/bin/ruby

class Customer
   def initialize(id, name, addr)
      @cust_id=id
      @cust_name=name
      @cust_addr=addr
   end
   def display_details()
      puts "Customer id #@cust_id"
      puts "Customer name #@cust_name"
      puts "Customer address #@cust_addr"
   end
end

# 创建对象
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

# 调用方法
cust1.display_details()
cust2.display_details()

这将产生以下输出-

Customer id 1
Customer name John
Customer address Wisdom Apartments, Ludhiya
Customer id 2
Customer name Poul
Customer address New Empire road, Khandala

Ruby 类变量

引用未初始化的类变量会产生错误,类变量与子类共享。

这是显示类变量用法的示例-

#!/usr/bin/ruby

class Customer
   @@no_of_customers=0
   def initialize(id, name, addr)
      @cust_id=id
      @cust_name=name
      @cust_addr=addr
   end
   def display_details()
      puts "Customer id #@cust_id"
      puts "Customer name #@cust_name"
      puts "Customer address #@cust_addr"
   end
   def total_no_of_customers()
      @@no_of_customers += 1
      puts "Total number of customers: #@@no_of_customers"
   end
end

# 创建对象
cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya")
cust2=Customer.new("2", "Poul", "New Empire road, Khandala")

# 调用方法
cust1.total_no_of_customers()
cust2.total_no_of_customers()

 这将产生以下输出-

Total number of customers: 1
Total number of customers: 2

Ruby 局部变量

分配给未初始化的局部变量也可以用作变量声明,变量开始存在,直到达到当前作用域的末尾。

在上面的示例中,局部变量是id,name和addr。

链接:https://www.learnfk.comhttps://www.learnfk.com/ruby/ruby-variables.html

来源:LearnFk无涯教程网

Ruby 常量

常量以大写字母开头,可以从该类或模块内访问在类或模块内定义的常量,而可以在全局访问在类或模块外定义的常量。

常量不能在方法内定义,引用未初始化的常量会产生错误,对已初始化的常量进行赋值会产生警告。

#!/usr/bin/ruby

class Example
   VAR1=100
   VAR2=200
   def show
      puts "Value of first Constant is #{VAR1}"
      puts "Value of second Constant is #{VAR2}"
   end
end

# Create Objects
object=Example.new()
object.show

VAR1和VAR2在这里是常量。这将产生以下输出-

Value of first Constant is 100
Value of second Constant is 200

Ruby 伪变量

它们是特殊变量,具有局部变量的函数,但行为类似于常量,您不能将任何值分配给这些变量。

  • self                      - 当前方法的对象。

  • true                     - 表示true的值。

  • false                    - 代表false的值。

  • nil                        - 表示未定义的值。

  •  __FILE__        - 当前源文件的名称。

  • __LINE__        - 源文件中的当前行号。

Ruby 整数

Ruby支持整数,整数可以从-2 30 到2 30-1 或-2 62 到2 62-1 。此范围内的整数是 Fixnum 类的对象,该范围之外的整数存储在 Bignum 类的对象中。

您可以使用可选的前导符号,可选的基数指示符(八进制为0,十六进制为0x或二进制为0b),然后在适当的基数中输入一串数字来写整数。

您还可以获取与ASCII字符相对应的整数值,或者通过在其前面加上问号来转义序列。

123                  # Fixnum decimal
1_234                # Fixnum decimal with underline
-500                 # Negative Fixnum
0377                 # octal
0xff                 # hexadecimal
0b1011               # binary
?a                   # character code for 'a'
?\n                  # code for a newline (0x0a)
12345678901234567890 # Bignum

Ruby 浮点数

Ruby支持浮点数。它们也是数字,但带有小数。浮点数是 Float 类的对象,并且可以是以下任意一种:

123.4                # floating point value
1.0e6                # scientific notation
4E20                 # dot not required
4e+20                # sign before exponential

Ruby 字符串

Ruby字符串只是8位字节的序列,它们是String字符串类的对象。双引号字符串允许替换和反斜杠表示法,但单引号字符串不允许替换,并且仅对\\和\'允许反斜杠表示法

#!/usr/bin/ruby -w

puts 'escape using "\\"';
puts 'That\'s right';

这将产生以下输出-

escape using "\"
That's right

您可以使用序列#{expr} 将任何Ruby表达式的值替换为字符串。在这里,expr可以是任何Ruby表达式。

#!/usr/bin/ruby -w

puts "Multiplication Value : #{24*60*60}";

这将产生以下输出-

Multiplication Value : 86400

有关Ruby字符串的更多详细信息,请访问 Ruby字符串

Ruby 数组

通过在方括号之间放置一系列用逗号分隔的对象引用来创建Ruby Array的文字。尾部逗号将被忽略。

#!/usr/bin/ruby

ary=[  "fred", 10, 3.14, "This is a string", "last element", ]
ary.each do |i|
   puts i
end

这将产生以下输出-

fred
10
3.14
This is a string
last element 

有关Ruby数组的更多详细信息,请访问 Ruby数组.

Ruby 哈希

通过在括号之间放置一系列键/值(Key/Value)对来创建文字Ruby哈希,在键和值之间使用逗号。

#!/usr/bin/ruby

hsh=colors={ "red" => 0xf00, "green" => 0x0f0, "blue" => 0x00f }
hsh.each do |key, value|
   print key, " is ", value, "\n"
end

这将产生以下输出-

red is 3840
green is 240
blue is 15

Ruby 范围

范围Ranges表示一个间隔,该间隔是一组具有开始和结束的值。可以使用s..e和s ... e文字或Range.new来构造范围。

使用..构造的范围从开始到结束都包括在内。使用...创建的那些不包括最终值。当用作迭代器时,range返回序列中的每个值。

range(1..5)表示包含1、2、3、4、5个值,range(1 ... 5)表示包含1、2、3、4个值。

#!/usr/bin/ruby

(10..15).each do |n| 
   print n, ' ' 
end

这将产生以下输出-

10 11 12 13 14 15

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

技术与商业案例解读 -〔徐飞〕

数据分析实战45讲 -〔陈旸〕

Python核心技术与实战 -〔景霄〕

Kafka核心技术与实战 -〔胡夕〕

全栈工程师修炼指南 -〔熊燚(四火)〕

编译原理实战课 -〔宫文学〕

HarmonyOS快速入门与实战 -〔QCon+案例研习社〕

PyTorch深度学习实战 -〔方远〕

工程师个人发展指南 -〔李云〕

好记忆不如烂笔头。留下您的足迹吧 :)