在Ruby中,代码重构可以通过以下方法使代码更简洁:
def calculate_total(price, tax_rate)
price * (1 + tax_rate)
end
total = calculate_total(100, 0.1)
def user_name=(new_name)
@user_name = new_name
end
class User
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def full_name
"#{@name} (#{@age})"
end
end
user = User.new("John", 30).full_name
module Loggable
def log(message)
puts message
end
end
class User
include Loggable
def initialize(name)
@name = name
end
end
user = User.new("John")
user.log("User created")
map
、reduce
、select
等,可以帮助你更简洁地处理数组和集合。numbers = [1, 2, 3, 4, 5]
squared_numbers = numbers.map(&:squared)
? :
语法,可以根据条件选择不同的值。status = if user.active?
"Active"
else
"Inactive"
end
and
、or
和not
关键字:这些关键字可以使条件表达式更简洁。user_is_adult = user.age >= 18 and user.active?
通过遵循这些实践,你可以使Ruby代码更简洁、易读和可维护。