数据类型
Ruby是一种动态类型语言,开发者无需明确声明变量的数据类型。Ruby根据分配给变量的值自动推断数据类型。
Integer 整型
表示整数。
number = 58
Float 浮点数
表示小数。
float_number = 3.14
Boolean 布尔值
表示真
或假
值。
is_true = true
is_false = false
String 字符串
表示字符序列。
text = "Hello, Ruby!"
Ruby提供了许多可以在字符串上执行的操作。
# 拼接
str1 = "Hello"
str2 = "World"
concatenated_str = str1 + ", " + str2
puts concatenated_str # => Hello, World
# 内插
name = "Alice"
greeting = "Hello, #{name}!"
puts greeting # => Hello, Alice!
# 长度
length = "This is a string".length
puts length # => 16
# 使用 << 进行拼接
str3 = "Hello"
str3 << ", " << "World"
puts str3 # => Hello, World
# 反转字符串
reversed_str = "Ruby".reverse
puts reversed_str # => ybuR
# 大写和小写
uppercase_str = "lite".upcase
puts uppercase_str # => LITE
lowercase_str = "RANK".downcase
puts lowercase_str # => rank
# 检查字符串是否包含子字符串
contains_substring = "Hello, World!".include?("World")
puts contains_substring # => true
# 提取子字符串
substring = "Hello, World!"[7..11]
puts substring # => World
# 将字符串拆分为数组
word_array = "This is a sentence.".split
puts word_array.inspect # => ["This", "is", "a", "sentence."]
# 去除空白
whitespace_str = " Trim me! "
trimmed_str = whitespace_str.strip
puts trimmed_str # => Trim me!
Symbol 符号
表示轻量级和不可变的标识符,通常用作哈希中的键。
# 创建符号
symbol1 = :apple
symbol2 = :orange
# 比较符号
puts symbol1 == symbol2 # => false
# 将字符串转换为符号
string = "banana"
symbol_from_string = string.to_sym
puts symbol_from_string # => :banana
# 将符号转换为字符串
symbol = :grape
string_from_symbol = symbol.to_s
puts string_from_symbol # => "grape"
# 检查符号是否存在于数组中
symbols = [:apple, :orange, :banana]
puts symbols.include?(:apple) # => true
puts symbols.include?(:watermelon) # => false
# 在哈希中使用符号作为键
fruit_counts = { :apple => 3, :orange => 5, :banana => 2 }
puts fruit_counts[:orange] # => 5
# 在哈希中迭代符号
fruit_counts.each do |fruit, count|
puts "#{fruit}: #{count}"
end
# =>
# apple: 3
# orange: 5
# banana: 2
Nil 空值
表示值的缺失。
empty_value = nil
Array 数组
表示有序的项集合。
numbers = [1, 2, 3, 4, 5]
Ruby中的数组提供了各种用于管理和操作元素集合的操作。
# 访问元素
puts numbers[0] # => 1
puts numbers[-1] # => 5 (最后一个元素)
# 将元素添加到数组末尾
numbers.push(6)
puts numbers.inspect # => [1, 2, 3, 4, 5, 6]
# 将元素添加到数组开头
numbers.unshift(0)
puts numbers.inspect # => [0, 1, 2, 3, 4, 5, 6]
# 从数组末尾删除元素
removed_element = numbers.pop
puts removed_element # => 6
puts numbers.inspect # => [0, 1, 2, 3, 4, 5]
# 从数组开头删除元素
removed_element = numbers.shift
puts removed_element # => 0
puts numbers.inspect # => [1, 2, 3, 4, 5]
# 检查数组是否包含特定元素
puts numbers.include?(3) # => true
# 查找元素的索引
index = numbers.index(4)
puts index # => 3
# 反转数组
reversed_numbers = numbers.reverse
puts reversed_numbers.inspect # => [5, 4, 3, 2, 1]
# 对数组进行排序
sorted_numbers = numbers.sort
puts sorted_numbers.inspect # => [1, 2, 3, 4, 5]
# 将数组元素连接成字符串
joined_string = numbers.join(', ')
puts joined_string # => 1, 2, 3, 4, 5
Range 区间
表示值的范围。
age_range = 20..30
区间还带有一套有用的操作。
# 创建区间
numeric_range = 1..5
puts numeric_range.to_a.inspect # => [1, 2, 3, 4, 5]
# 将区间转换为数组
range_array = (1..3).to_a
puts range_array.inspect # => [1, 2, 3]
# 包含区间(包括1和5)
inclusive_range = 1..5
puts inclusive_range.to_a.inspect # => [1, 2, 3, 4, 5]
# 非包含区间(不包含5)
exclusive_range = 1...5
puts exclusive_range.to_a.inspect # => [1, 2, 3, 4]
# 检查值是否在区间范围内
puts numeric_range.include?(3) # => true
puts numeric_range.include?(8) # => false
# 获取开始值和结尾值
puts numeric_range.begin # => 1
puts numeric_range.end # => 5
# 区间步长值
stepped_range = 1..10
stepped_range_step_2 = stepped_range.step(2)
puts stepped_range_step_2.to_a.inspect # => [1, 3, 5, 7, 9]
Hash 哈希
表示键值对的集合。以下是哈希的一些常见操作:
# 创建哈希
person = { "name" => "John", "age" => 30, "city" => "New York" }
# 使用键访问值
puts person["name"] # => John
puts person["age"] # => 30
# 添加新的键值对
person["occupation"] = "Engineer"
puts person.inspect
# => {"name"=>"John", "age"=>30, "city"=>"New York", "occupation"=>"Engineer"}
# 更新现有键的值
person["age"] = 31
puts person.inspect
# => {"name"=>"John", "age"=>31, "city"=>"New York", "occupation"=>"Engineer"}
# 删除键值对
person.delete("city")
puts person.inspect
# => {"name"=>"John", "age"=>31, "occupation"=>"Engineer"}
# 检查键是否存在
puts person.key?("name") # => true
puts person.key?("gender") # => false
# 获取所有键或值
keys = person.keys
values = person.values
puts keys.inspect # => ["name", "age", "occupation"]
puts values.inspect # => ["John", 31, "Engineer"]
# 迭代键值对
person.each do |key, value|
puts "#{key}: #{value}"
end
# 输出:
# name: John
# age: 31
# occupation: Engineer
# 检查哈希是否为空
puts person.empty? # => false
# 清除哈希中的所有键值对
person.clear
puts person.inspect # => {}
Regexp 正则表达式
表示用于字符串匹配的模式。
pattern = /pattern/
以下是Ruby中一些常见的正则表达式操作:
# 匹配模式
pattern = /world/
result = "hello world" =~ pattern
puts result # => 6 (index where the pattern starts)
# 检查字符串中是否存在模式
contains_pattern = "hello world" =~ /world/
puts contains_pattern.nil? ? "Not found" : "Found" # => Found
# 匹配模式的多个匹配项
matches = "hello world and world again".scan(/world/)
puts matches.inspect # => ["world", "world"]
# 不区分大小写匹配
case_insensitive_match = "Hello World" =~ /world/i
puts case_insensitive_match.nil? ? "Not found" : "Found" # => Found
# 捕获组
text = "Lite Rank"
match = text.match(/(\w+) (\w+)/)
puts match[0] # => John Doe (entire match)
puts match[1] # => John (first captured group)
puts match[2] # => Doe (second captured group)
# 替换
new_text = "Hello, Alice!".gsub(/Alice/, "Bob")
puts new_text # => Hello, Bob!
# (^和$)匹配行的开头和结尾
starts_with_hello = "hello world" =~ /^hello/
puts starts_with_hello.nil? ? "Not found" : "Found" # => Found
ends_with_world = "hello world" =~ /world$/
puts ends_with_world.nil? ? "Not found" : "Found" # => Found
Set 集合
Set
是无序的、唯一元素的集合。
require 'set'
my_set = Set.new([1, 2, 3, 4, 5])
puts my_set # => #<Set: {1, 2, 3, 4, 5}>
代码挑战
写一段程序,以句子字符串为输入,以哈希表为输出。其中,键是句子中去重后的单词,值是每个单词的出现频次。
应该输出:
{"the"=>2, "quick"=>1, "brown"=>1, "fox"=>1, "jumps"=>1, "over"=>1, "lazy"=>1, "dog"=>1}
。
Loading...
> 此处输出代码运行结果