I am sitting in the airport right now, waiting for my twice delayed flight to board. The security man took my Scope. He does not want my teeth to be clean or my breath to be fresh. So be it.
Here’re two classes you may or may not have seen before. Unlike, say, a small bottle of refreshing mouth wash, you can definitely take these guys on an airplane.
Struct
Struct is like Ruby on Rails for classes. Scaffolding. It lets you quickly cobble together a new class with some gettable-settable attributes. You can then instantiate your struct’d class and go nuts. You don’t even need to require anything—Struct is right there, ready and willing, all the time.
When I was little we had a black lab named Tucker. He was a dog with four legs and two eyeballs.
>> Animal = Struct.new(:name, :legs, :eyeballs) => Animal >> tucker = Animal.new('dog', 4, 2) => #<struct Animal name="dog", legs=4, eyeballs=2> >> tucker.legs => 4 >> tucker.legs = 3 => 3 >> tucker.legs => 3
Wow, that’s quick. We didn’t have to set up a class definition or fumble with attr_accessor. But there’s more.
>> tucker[0] => "dog" >> tucker['name'] => "dog" >> tucker[:name] => "dog" >> tucker[:name] = 'doggy' => "doggy" >> tucker.name => "doggy"
It’s like Array and Hash got married and had a little classling. Okay, that’s not true, but it sure looks that way from the outside. I wonder if that means Struct objects are enumerable?
>> tucker.is_a? Enumerable => true >> tucker.methods.grep /each/ => ["each_with_index", "each", "each_pair"]
How unexpected. And it’s ordered, too—the order you passed your keys when creating your struct’d class is maintained. In this case the order is name, legs, then eyeballs. Always.
>> tucker.each_pair { |k,v| puts "key: #{k}, value: #{v}" } key: name, value: dog key: legs, value: 4 key: eyeballs, value: 2 => #<struct Animal name="dog", legs=4, eyeballs=2> >> tucker.each { |v| puts v } dog 4 2 => #<struct Animal name="dog", legs=4, eyeballs=2>
For reference:
>> (tucker.methods & Enumerable.instance_methods).sort => ["all?", "any?", "collect", "detect", "each_with_index", "entries", "find", "find_all", "grep", "include?", "inject", "map", "max", "member?", "min", "partition", "reject", "select", "sort", "sort_by", "to_a", "zip"]
Since a struct’d class is not actually a Hash or an Array, there are differences. A Struct instantiated object has no keys—it has members.
>> tucker.members => ["name", "legs", "eyeballs"] >> tucker.values => ["doggy", 4, 2]
Also: you can not add new members arbitrarily as you can with an Array or a Hash. However many members you instantiate your struct’d class with is however many you’re stuck with. As a result: no merge, update, or concat (+). This is a class, after all. Not a fancy faux-primitive.
If you need to turn a Struct object into a Hash, here’s an easy way:
>> hash = Hash[*tucker.members.zip(tucker.values).flatten] => {"name"=>"doggy", "eyeballs"=>2, "legs"=>4}
Maybe wrap that in a to_hash if you’d like. For to_a, just use values.
It’s worth noting that since everything in Ruby is an object, we can inherit straight from a call to Struct.new. Maybe we want to add some questions?
class Primate < Struct.new(:name, :legs, :eyeballs) def legs? (legs && legs.to_i > 0) ? true : false end end
Imagine the possibilities. Fake-out ActiveRecord objects in your tests! Mock hashes that are super indifferent! Create resources which can only be described as active! Amaze your friends!
OpenStruct
OpenStruct is a bit more liberal than Struct, with less structure. Like that hippie cousin everyone has. (in my family it’s me)
Usage: pass a hash to OpenStruct.new, receive an object with full-on getters and setters. Because this behavior is a bit suspect we must explicitly require OpenStruct (ostruct) from the standard library. Like YAML.
>> require 'ostruct' => true >> scope = OpenStruct.new(:brand => 'Scope', :owner => 'P&G', :flavor => 'Cinnamon Ice') => #<OpenStruct brand="Scope", owner="P&G", flavor="Cinnamon Ice"> >> scope.brand => "Scope" >> scope.brand = 'Scoped' => "Scoped" >> scope.brand => "Scoped"
Unlike Struct, we can add new members to an OpenStruct object whenever we’d like.
>> scope.tasty => nil >> scope.tasty = true => true >> scope.tasty => true
This is accomplished through some method_missing-like magic. Unfortunately, this means all your NoMethodError exceptions go away.
>> scope.something_fake => nil
Not the biggest deal. That’s how hashes work when you try to access a non-existent key, after all. And there’s always good ol’ respond_to:
>> scope.respond_to? :something_fake => false
So that’s all pretty cool. I’ve been playing with this class in my code lately. Mainly in tests to fake out ActiveRecord stuffs, as I suggested with Struct. There is one major disadvantage to OpenStruct: it’s not enumerable. Less structure, see. You can not each, you can not members, you can’t even values. Well. I mean. Out of the box you can’t.
Enum-o-Struct
What we’re going to do is make OpenStruct enumerable by adding the each method, the members method, and including the Enumerable module.
require 'ostruct' class EnumoStruct < OpenStruct include Enumerable def members methods(false).grep(/=/).map { |m| m[0...-1] } end def each members.each do |method| yield send(method) end self end end
Cryptic? Hardly.
We want an each method. How are we going to enumerate over an OpenStruct? Well, we could always just pass the return value of each getter-method to whatever block is passed to our each method. If that’s our approach, it looks like we need a way to find all the members. All the getters.
While an OpenStruct object may have a ton of arbitrary methods, it has setters which end in an equal sign and almost always correspond to a getter. The members method here finds all methods ending in = on an object by grabbing an array of methods excluding those defined on parent/ancestor classes (methods(false)) and creating an array of methods which match a regular expression, using grep. It then strips the last character, the =, from each found method, returning our array of members.
The members from our scope example: [“flavor”, “owner”, “brand”]
The Enumerable module depends on your class implementing each to work its magic. The concept is simple: go through each of the member methods and call the method, passing its value into the block passed to each using yield. In this case, send(method) is the same as, for example, self.flavor or self.brand.
Notice we return self in our each method: it’s polite for each to return self so that calls to it may be chained.
In action:
>> require 'enumostruct' => true >> scope = EnumoStruct.new(:brand => 'Scope', :owner => 'P&G', :flavor => 'Cinnamon Ice') => #<EnumoStruct brand="Scope", owner="P&G", flavor="Cinnamon Ice"> >> scope.each { |v| puts "value: #{v}" } value: Cinnamon Ice value: P&G value: Scope => #<EnumoStruct brand="Scope", owner="P&G", flavor="Cinnamon Ice">
Oh that’s delicious. Remember, now we have all the Enumerable methods.
>> scope.map { |v| v } => ["Cinnamon Ice", "P&G", "Scope"] >> scope.detect { |v| v =~ /&/ } => "P&G"
Hey, I liked that each_pair method that Struct gives you. Let’s add it before we go.
class EnumoStruct < OpenStruct def each_pair members.each do |method| yield method, send(method) end self end end >> scope.each_pair { |k,v| puts "key: #{k}, value: #{v}" } key: flavor, value: Cinnamon Ice key: owner, value: P&G key: brand, value: Scope => #<EnumoStruct brand="Scope", owner="P&G", flavor="Cinnamon Ice">
Same as each, really. The only difference is we pass the name of the current member into the block as the first argument. Cake.
Finally, let’s be really cheap. Let’s add [] and []= to our Enum-o-Struct. Are you in?
class EnumoStruct < OpenStruct def [](member) send(member) end def []=(member, value) send("#{member}=", value) end end >> scope['owner'] => "P&G" >> scope[:website] = 'http://www.getclose.com' => "http://www.getclose.com" >> scope.website => "http://www.getclose.com" >> scope[:negative] => nil
Now don’t go too crazy, okay? Always monkeypytch with caution.
Bye!
Ah, we’ve accomplished so much. My only hope is you can truly find a use for one of these humble classes. They are not flammable and pose no threat to your fellow passengers.
And I bet your Tucker would have done better on Dancing With The Stars.
Great article.
I see the fruits of our experimentation :)
I like your blog. So many good articles. Here I find things I don’t knew -> Struct or OpenStruct.
Thank you.
Hi,
cool, I knew both before, but adding methods to them never occured to me…
Anyway, I’d expect members to return something here:
irb(main):001:0> require 'ostruct' => true irb(main):002:0> irb(main):003:0* irb(main):004:0* class EnumoStruct < OpenStruct irb(main):005:1> include Enumerable irb(main):006:1> irb(main):007:1* def members irb(main):008:2> methods(false).grep(/=/).map { |m| m[0...-1] } irb(main):009:2> end irb(main):010:1> irb(main):011:1* def each irb(main):012:2> members.each do |method| irb(main):013:3* yield send(method) irb(main):014:3> end irb(main):015:2> self irb(main):016:2> end irb(main):017:1> end => nil irb(main):018:0> o = OpenStruct.new => #<openstruct> irb(main):019:0> o.foo= nil => nil irb(main):020:0> o.bar= :barbaz => :barbaz irb(main):021:0> o.members => nilAny ideas why it doesn’t?
Stephan: Use o = EnumoStruct.new. You’re defining a new class and then instantiating the old one – you need to use the EnumoStruct class you just created.
OpenStruct is cool, but watch for gotchas with freeze and using attribute names that are already defined methods.
Oh dear, apparently I’m too used to opening existing classes already…
I had problems getting the members-thing to work:
And then I discovered marshal_dump:
That does it for me.
how about this instead
class OpenStruct def table; @table; end end
so…
o = OpenStruct.new o.a = 1 o.b = 2 o.table.each_pair do etc…
Hmm, if I place all those methods in one class the two [] methods return nil which makes me think where the enumerable is included makes a big difference. Has any one got all these methods to work in one class?
Cheers
Great post, thanks. good jokes
Tattoos Celtic Tattoos Lower Back Tattoos Dragon Tattoos Skull Tattoos Heart Tattoos Butterfly Tattoos Chinese Tattoos Layered Hair Styles Layered Hairstyles Emo Hairstyles Medium Hairstyles Bang Hairstyle Prom Hairstyle Hair Coloring Heart Lower Back Tattoos
For anyone with old or elderly loved ones, it is important to take care of your central florida retirement communities brookdale senior living inc kelly home care services boston senior home care senior home care inc new jersey living will form new jersey living will senior day care centers florida golf retirement communities senior apartments in las vegas senior apartments las vegas in hopes making sure you or your old / elderly loved ones are taken care of with the best nursing care available
sikiş porno sex video izle iyi porno uzun porno yeni pornolar porno seyret sex seyret porno filmler sex izleyin sex izle porno sex erotik porn video türk porno canlı porno porno izle porno porno film sex filmleri porn video porno film sex seyret porno video seyret orgazm porno seks izle erotik video sex videolar yetişkin video sex video izle porno video izle bedava porno 18 video seks porno sıcak izle yetişkin film sikiş seyret sex amatör videolar teen video erotik videolar yetişkin video yetişkin videolar pornolar porno video teen kızlık bozma sikiş sikiş video seks türban sex sex erotik seks izle sıcak ateşli
modern abstract art sofa manufacturer гранит 净水器 混合机 过滤机 DHL快递 保险箱 法兰 法兰标准 牛皮癣 皮肤病 北京快递公司 北京国际快递 传世私服 传奇世界私服 天龙八部私服 天龙私服 网络电话 免费网络电话 假发 补发 织发 植发 上海搬家公司 上海搬场公司 大众搬家 大众搬场 张家界旅游 香港旅游 深圳旅行社 打包机 收缩机 萎缩性胃炎 neoprene laptop bags SEO优化 SEO优化 计量泵 胃炎 胃病 冷水机 冰水机 工业冷水机 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 油罐车 北京办证 办证 北京特价机票 北京打折计票 北京国际机票 北京机票预定 北京飞机票 北京订机票 北京机票查询 血糖仪 血糖仪 银杏 水培花卉 企业宣传片 空分设备 机电设备安装 代孕 代孕网 代孕 代孕 代孕 试管婴儿 代孕 电话交换机 程控交换机 集团电话 集装袋 混合机混合机 混合机捏合机 捏合机 捏合机导热油炉 导热油炉 导热油炉 反应釜 反应釜 反应釜 回流焊 波峰焊 spherical roller bearing 搬运车 搬运车 电动搬运车 油桶搬运车 堆高车 电动堆高车 半电动堆高车 堆垛车 高空作业平台车 电动叉车 平衡重叉车 前移叉车 电瓶叉车 苗木价格 苗木信息 标牌制作 深圳标牌 儿童摄影 北京儿童摄影 防静电鞋 淘宝刷信誉 威海凤凰湖 威海海景房 大庆密封件 打标机 淘宝刷信誉 TESOL/TEFL国际英语教师证书 英语教师进修及培训 韩国饰品批发 代写论文 代写论文 代写论文 代写代发 论文代写 电源模块 模块电源 X架 超薄灯箱> 易拉宝 展柜制作 代理服务器 游戏加速器 网络加速器 网通加速器 电信加速器 电信网通转换器 电信网通加速器 网通电信互转 网通电信互通 网络游戏加速器 美国VPN代理 美国独享VPN 美国独享IP pvc ceiling panel Spherical roller bearings 天龙八部私服 SEO优化 安全鞋 劳保鞋 防砸鞋 电绝缘鞋 上海安全鞋 上海劳保鞋 江苏劳保鞋 服装软件 服装管理软件 进销存软件 进销存管理软件 服装管理系统 服装进销存软件 进销存系统 进销存管理系统 免费进销存软件 吉林中医 东北特产 打包机 dhl 阳痿 阴茎短小 阴茎增大 早泄 前列腺炎 阴茎增粗 阴茎延长 国际机票 上海国际机票 国际打折机票 国际特价机票 CRM 客户管理软件 客户关系管理 免费客户管理软件 客户管理软件下载 客户信息管理系统 销售管理系统 销售管理 CRM系统 CRM软件 客户关系管理系统 客户关系管理软件 客户管理 客户管理系统 营销管理系统 客户资源管理 销售管理软件 客户资料管理软件 客户资源管理软件 客户信息管理软件 客户资料管理 客户资源管理 客户信息管理 客户资料管理系统 客户资源管理系统 客户管理软件免费版 砂磨机 砂磨机 砂磨机 卧式砂磨机 卧式砂磨机 卧式砂磨机 三辊研磨机 三辊研磨机 三辊研磨机 混合机 混合机 混合机 锥形混合机 锥形混合机 锥形混合机 行星动力混合机 行星动力混合机 行星动力混合机 无重力混合机 无重力混合机 无重力混合机 干粉砂浆设备 干粉砂浆设备 干粉砂浆设备 捏合机 捏合机 捏合机 导热油炉 导热油炉 导热油炉 反应釜 反应釜 反应釜 搪玻璃反应釜 搪玻璃反应釜 搪玻璃反应釜 乳化机 涂料设备 干混砂浆设备 无重力混合机 胶体磨 涂料成套设备 双螺旋混合机 北京婚庆 北京婚庆公司 400电话 办证 呼吸机 制氧机 亚都 亚都加湿器 亚都净化器 亚都装修卫士 饰品批发 小饰品批发 韩国饰品 韩国饰品批发 premature ejaculation penis enlargement 破碎机 制砂机 球磨机 雷蒙磨 雷蒙磨粉机 鄂式破碎机 鄂式破碎机 免烧砖机 加气混凝土设备 反击式破碎机 选矿设备 安利产品 马来西亚留学 网站优化 网站推广 衬布 代写论文 代写论文 代写论文 论文代写 代写论文 代写硕士论文 代写毕业论文 磁力泵 离心泵 化工泵 隔膜泵 螺杆泵 潜水泵 油泵 耐腐蚀泵 泵 水泵 拖链 防护罩 排屑机 塑料拖链 钢铝拖链 水泵 磁力泵 隔膜泵 离心泵 液下泵 自吸泵 多级泵 排污泵 螺杆泵 油泵 化工泵 电动隔膜泵 气动隔膜泵 自吸式磁力泵 氟塑料磁力泵 管道离心泵 导热油泵 深井泵 潜水泵 污水泵 潜水排污泵 深圳装饰 深圳装饰公司 深圳装修公司 特价机票 打折机票 国际机票 机票 新风换气机 换气机 立式新风换气机 风机箱 新风系统 能量回收机 搅拌机 混合机 乳化机 分散机 毛刷 毛刷辊 工业毛刷 刷子 钢丝刷 涂层测厚仪 硬度计 兆欧表 激光测距仪 测振仪 转速表 温湿度计 风速仪 超声波测厚仪 粗糙度仪 噪音计 红外测温仪 万用表 硬度计 万用表 美容院 美容加盟 澳洲留学 澳大利亚留学 什么是法兰 电烤箱 酒店预定 北京酒店预定 北京酒店 离心机 nail equipment nail products nail product nail uv lamp nail uv lamp nail uv lamps uv nail lamp nail brush nail file nail tool nail tip nail gel curing uv lamps lights 万用表 风速仪 红外测温仪 噪音计
情趣用品,情趣用品,情趣用品,情趣用品,情趣用品,情趣,情趣,情趣,情趣,情人歡愉用品,情惑用品性哥,情人用品性哥,情趣用品,AIO交友愛情館,情人歡愉用品,美女視訊,情色交友,情人用品性哥,視訊交友,辣妹視訊,美女交友,性愛,嘟嘟成人網,按摩棒,震動按摩棒,微調按摩棒,情趣按摩棒,逼真按摩棒,G點,跳蛋,跳蛋,跳蛋,性感內衣,飛機杯,充氣娃娃,情趣娃娃,角色扮演,性感睡衣,後庭區,SM,潤滑液,情趣禮物,威而柔,香水,精油,芳香精油,自慰,自慰套,性感吊帶襪,情趣用品加盟,情人節禮物,情人節,吊帶襪,辣妹視訊,美女交友,情色交友,成人交友,視訊聊天室,美女視訊,視訊美女,情色視訊,免費視訊聊天,視訊交友,視訊聊天,AIO交友愛情館,嘟嘟成人網,成人貼圖,成人網站,AIO交友愛情館,情色,情色貼圖,情色文學,情色交友,色情聊天室,色情小說,七夕情人節,色情,A片,A片下載,免費A片,免費A片下載,情色視訊,情色電影,色情網站,辣妹視訊,視訊聊天室,情色視訊,免費視訊聊天,視訊聊天,美女視訊,視訊美女,美女交友,美女,情色交友,成人交友,自拍,本土自拍,情人視訊網,視訊交友90739,生日禮物,情色論壇,正妹牆,正妹,成人網站,A片,免費A片,A片下載,免費A片下載,AV女優,成人影片,色情A片,成人論壇,情趣,免費成人影片,成人電影,成人影城,愛情公寓,色情影片,保險套
Thanks so much for this! This is exactly what I was looking for
mirc mırc mırç mirç mirc indir mirc yükle mirc yukle türkçe mirc mirc indir mirc islami sohbet kelebek kelebek script kelebek sohbet kelebek mirc chat çet cet çet odaları sohbet kanalları sohbet odaları kameralı sohbet kameralı chat sohbet eğlence mirc sohbet odaları sevgili arkadaş arkadaş bul arkaraş ara oto araba şarkı sözleri astroloji ikinci el telefon gazete gazeteler günlük gazeteler marifetname bedava domain ücretsiz domain benimurl parça kontör parça kontör radyo dinle bedava blog ücretsiz blog
video ödev indir şarkı sözleri video izle şiir türkü indir güzel sözler fıkra porno izle pornolar 18
Victorias Secret Victoria’s Secret Fashion show Victorias Secret Pink Victorias Secret Model Victorias Secret Credit Card Victorias Secret Coupon Code Victorias Secret Lingerie Victorias Secret Fashion Show 2005 Victorias Secret Fashion Show 2006 Victorias Secret Bra Victorias Secret Catalog Victorias Secret Pantie Victorias Secret Online Coupon Victorias Secret Fashion Show 2007 Victorias Secret Girl Free Shipping Victorias Secret Victorias Secret Home Victorias Secret Christmas Victoria’S Secret Pink Dog Victorias Secret Music Victorias Secret Semi Annual Sale Victorias Secret Jobs Victorias Secret Free Shipping Code Victorias Secret Shoes Victorias Secret Thong Victorias Secret Commercial Victorias Secret Promotional Code Victorias Secret Love Spell Victorias Secret Boots Victorias Secret Employment Victorias Secret Reviews Victorias Secret Jeans Victorias Secret Brasil Victorias Secret Bag
情人用品,情人用品性哥,情 人用品,情趣用品,視訊交友,視訊美女,視訊美女,視訊交友網,視訊聊天室,視訊聊天室,視訊 交友網,免費視訊聊天,辣妹視訊,辣妹視訊,情人視訊網
徵信社,案件討論,男女專區,法律諮詢,相關新聞,情趣用品,情趣用品,情趣精品,情趣用品,情趣用品,情趣用品,情趣用品,威而柔,自慰套,自慰套,SM,充氣娃娃,充氣娃娃,潤滑液,飛機杯,按摩棒,跳蛋,性感睡衣
威而柔,自慰套,自慰套,SM,充氣娃娃,充氣娃娃,潤滑液,飛機杯,按摩棒,跳蛋,性感睡衣,視訊交友90739,情人視訊網,情色交友,視訊交友,辣妹視訊,美女視訊,aio交友愛情館,情色論壇,成人論壇,免費視訊聊天,辣妹視訊,視訊交友網,美女視訊,視訊交友,成人視訊,情趣用品,成人聊天室,情趣,情趣,視訊聊天室,視訊聊天,視訊聊天室,情色視訊,情人視訊網,免費視訊聊天室,aio交友愛情館,色情遊戲,寄情築園小遊戲,情色文學,一葉情貼圖片區
:-)))) Very interesting! Thanks!!! phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex phone sex mootzie cosmology edvard munch humorous quotations hundredth monkey brain teasers jillian ann shakespeare quotations bride of frankenstein gettysburg address bill of rights van gogh bowling tips violin books eden prosper julia dreyfus violin bows chess download xslt aviation funny quotes xslt tips gothic abs self hypnosis gothic clothes monique olivia noda amanda roberts somethings happening bgreen68 bfire3 reldeve links psychology hypnosis phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex phonesex mootzie buffys bedroom blog the great adventure