48 Specific ways to write better ruby
杰瑞发布于2025-03-04
48 Specific ways to write better ruby
- 6.Object:
对象是变量的容器,称为实例变量,并代表对象的状态,特殊内部变量-连接唯一的类;类是方法和常量的容器,是它的所有实例的方法。 超类就是类的父类,有特殊变量跟踪超类。模块和类的区别是模块没有new方法;单例类。。。再定义类的方法self..会生成一个匿名的类在实例的链条上.
BasicObject> Kernel> Object >SomeModuleInPerson > Person > Customer.
Customer.singleton_class.instance_methods(false) 查看单例类。
Customer.superclass; Customer.ancestors; Customer.included_modules;- 12. == 等价has 4个部分的检查:
"foo" == "foo" => true; "foo".equal?("foo") => false; == 会做隐式转换。 1== 1.0 => true; ;equal? 意味着 object_id (同一个内存块); case表达式使用 ===; Regexp 类定义了=== ,所以 /er/ === "Her" is true, but "Her" === /er/ is false; [1,2,3].is_a(Array) true; [1,2,3] === Array => false; Array === [1,2,3] => true; === 接受者=== 参数 means 参数.is_a?(接受者);- 19. reduce方法折叠集合:
Enumerable模块的类,可对集合进行过滤,遍历和转化。map和select;还有个可以管理一切的方法 reduce(or inject), reduce可以转换结构;接受者,每个元素被调用一次,并产生返回值,累加器。 enum.reduce(0){|accumulator, element| accumulator + element} 0初始值;建议你总是使用一个带有起始值的累加器。 enum.reduce(0, :+);
数组转成Hash; array.reduce({}) {|hash, element| hash.update(element => true)}
users.select{|u| u.age>=21}.map(&:name) 获取大于等于21的names数组。比较低效;
User.reduce([]) {|names, user| names << user.name if user.age >=21 ; names}- 22. raise:
raise("coffee machine low on water") => raise(RuntimeError, "coffee machine low on water")
异常的处理是基于类型的。Exception or StandardError ; class CoffeeTooWeakError < StandardError; end
raise(CoffeeTooWeakError, "coffee to water ratio too low")
super("invalid temperature: #@temperature") raise(TemperatureError.new(180))