词汇:hash
n. 剁碎的食物;混杂,拼凑;重新表述
相关场景
- 30.define_method or method_missing:
- 如果没有找到任何方法,method_missing就会被执行;但是因为又super的原因,这里会有迷惑。def method_missing(name, *args, &block) if @hash.respond_to?(name) @hash.send(name, *args, &block) else super end end; Hash.public_instance_methods(false).each do |name| define_method(name) do |*args, &block| @hash.send(name, *args, &block) end; h.public_methods(false).sort.take(5); 实现了Hash的方法。
AuditDecorator @logger = Logger.new($stdout); private def method_messing(name, *arg, &block) @logger.info("calling '#{name}' on #{@object.inspect}"); @object.send(name, *args, &block); define_method更加适合做这个了。 mod=Module.new do object.public_methods.each do |name| define_method(name) do |*args, &block| @logger.info("") @object.send(name, *args, &block) end end end extend(mod) ; 创建了一个匿名的模块。 —— define_method恢复了内省方法。。 respond_to? and respond_to_missing?>> Effective Ruby- 21.对集合和核心类优先使用委托而非继承:
- is a,还是 has a, 委托就是有一个。。。require('forwardable'); class RaisingHash extend(Forwardable) include(Enumerable) def_delegators(@hash, :[], :[]=, :delete, :each, :keys, :values, :length, :empty?, :has_keys) end Forwardable模块让使用委托的过程变得容易。 del_delegator(@hash, :delete, :erase!)>> Effective Ruby
- 20. Hash的初始值:
- Hash.new(10); h[:missing_key] => 10; h={}; h[:weekdays] = h.fetch(:weekdays, []) << "Monday" ---> ["Monday"]>> Effective Ruby
- 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}>> Effective Ruby- 18. 标准库里面的Set:
- Array#include? 的时间复杂度是O(n),数量变多,时间就边长。Hash#include? O(log n); Hash[permissions.map{|p|} [p,true]]; require('set'); @permissions= Set.new(permissions) ; Set是一个无序容器。有序容器SortedSet类。如果不需要顺序,又存在很多条记录要判断是否Include?(x),那么Set是最好的选择。>> Effective Ruby
- 10. Struct or Hash:
- key-value 用hash; hash 作为公共接口是没有访问限制的。Reading = Struct.new(:data, :high, :low); Reading.new(Date.parse(..),..,..) Struct是属性列表;里面也可以定义方法; 将Struct返回值设置为常量,像类一样使用他。>> Effective Ruby
- WILL:
- So what'd I think? I'm holdin' out for somethin' better. I figure I'll eliminate the middle man. Why not just shoot my buddy, take his job and give it to his sworn enemy, hike up gas prices, bomb a village, club a baby seal, hit the hash pipe and join the National Guard? Christ, I could be elected President.>> Good Will Hunting (1997)Movie Script
- I want some red flannel hash, Harold.>> Stay Hungry Movie Script
- I'm gonna order hash up here one day.>> Stay Hungry Movie Script