在Ruby编程语言中,习语(idioms)是一些常用的、简洁的表达方式,用于表示常见的编程模式和实践。以下是一些常见的Ruby习语:
"Hello, World!".upcase
if x > 10
puts "x is greater than 10"
elsif x > 5
puts "x is greater than 5"
else
puts "x is less than or equal to 5"
end
numbers = [1, 2, 3, 4, 5]
sum = numbers.inject(0) { |acc, elem| acc + elem }
numbers = [1, 2, 3, 4, 5]
squared_numbers = numbers.map { |n| n * n }
module Math
PI = 3.141592653589793
def self.sqrt(n)
Math.sqrt(n)
end
end
class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def to_s
"#{name}, #{age} years old"
end
end
begin
# some code that might raise an exception
rescue StandardError => e
puts "An error occurred: #{e.message}"
ensure
# code that will always be executed, regardless of whether an exception was raised
end
这些习语是Ruby编程中非常重要的一部分,可以帮助开发人员编写更简洁、更易读的代码。
没有搜到相关的文章