- 浏览: 244729 次
- 性别:
- 来自: 杭州
文章分类
- 全部博客 (173)
- ruby (38)
- rails (42)
- javascript (7)
- jquery (1)
- linux (15)
- design patterns (1)
- project management (6)
- IT (7)
- life (19)
- data structures and algorithm analysis (2)
- css (1)
- prototype (1)
- mysql (4)
- html (1)
- git (3)
- novels (1)
- c (1)
- Latex (13)
- erlang (1)
- 求职 (1)
- API (0)
- Shell (4)
- Rabbit MQ (1)
- 计算机基础 (1)
- svn (2)
- 疑问 (1)
最新评论
-
zhangyou1010:
回去倒立去,哈哈。
作为一个程序员,身体很重要! -
Hooopo:
Ruby MetaProgramming is all abo ...
Metaprogramming Ruby -
orcl_zhang:
yiqi1943 写道LZ现在上学还是工作呢工作好多年了。不过 ...
2011年 -
yiqi1943:
LZ现在上学还是工作呢
2011年 -
tjcjc:
query cache
就是一个简单的hash
key就是sq ...
Rails sql延迟加载和自带缓存
1,先看api
2,to_proc经常和&一起使用.
可以把block传递给带block的方法.block的to_proc返回的就是本身.
如果对象自带to_proc方法的话,就可以把它当作带"&"的参数传给带block方法(默认状态下,Proc、Method对象都有to_proc方法)。方法调用时会执行to_proc,它将返回Proc对象.
3,to_proc和method_missing
4,Going crazy
可以让&使用多个参数,更性感。
What I always regretted though was not being to pass any arguments, so I hacked and monkeypatched a bit, and got:
Not that this is any shorter than just creating the darn block in the first place. But hey, it’s a good exercise in metaprogramming and show of more of Ruby’s awesome flexibility.
After this I remembered something similar that annoyed me before. It’s that Rails helper methods are just a bag of methods available to, because they are mixed in your template. So if you have an array of numbers that you want to format as currency, you’d have to do:
What if I could apply some to_proc-love to that too? All these helper methods cannot be added to strings, fixnums, and the likes; that would clutter way to much. Rather, it might by a nice idea to use procs that understands helper methods. Here is what I created:
I used a clean blank class (in Ruby 1.9, you’d want to inherit it from BasicObject), in which I will provide the proper proc-object. I play around with the argument list a bit, handling multiple arguments and blocks too. You can now use this syntax:
That is a lot sexier if you as me. And you can use it in any object, not just inside views. And lets add some extra arguments and some Enumerator-love too:
In case you are wondering, the position you can specify is to tell where the arguments need to go. Position 0 is the method name, so you shouldn’t use that, but any other value is okay. An example might be that you cant to wrap an array of texts into span-tags:
So there you have it. I’m probably solving a problem that doesn’t exist. It is however a nice example of the awesome power of Ruby. I hope you’ve enjoyed this little demonstration of the possible uses of to_proc.
最后的一部分来自于http://iain.nl/2010/02/going-crazy-with-to_proc/
引用
Method#proc
meth.to_proc => prc
Returns a Proc object corresponding to this method.
prc.to_proc → prc
Part of the protocol for converting objects to Proc objects. Instances of class Proc simply return themselves.
meth.to_proc => prc
Returns a Proc object corresponding to this method.
prc.to_proc → prc
Part of the protocol for converting objects to Proc objects. Instances of class Proc simply return themselves.
2,to_proc经常和&一起使用.
可以把block传递给带block的方法.block的to_proc返回的就是本身.
如果对象自带to_proc方法的话,就可以把它当作带"&"的参数传给带block方法(默认状态下,Proc、Method对象都有to_proc方法)。方法调用时会执行to_proc,它将返回Proc对象.
pobj = lambda {|v| p v } [1,2,3].each(&pobj) => 1 2 3
class Foo def to_proc lambda {|v| p v} end end [1,2,3].each(&Foo.new) => 1 2 3
class Symbol def to_proc proc { |obj, *args| obj.send(self, *args) } end end projects.collect(&:name) [1, 2, 3].map(&:to_s.to_proc) #=> ["1", "2", "3"]
class Person < ActiveRecord::Base; end; [{:name => 'Dan'}, {:name => 'Josh'}].map(&Person.method(:new)) class Class def to_proc proc(&method(:new)) end end [{:name => 'Dan'}, {:name => 'Josh'}].map(&Person)
3,to_proc和method_missing
module Kernel protected def it() It.new end alias its it end class It undef_method(*(instance_methods - %w*__id__ __send__*)) def initialize @methods = [] end def method_missing(*args, &block) @methods << [args, block] unless args == [:respond_to?, :to_proc] self end def to_proc lambda do |obj| @methods.inject(obj) do |current,(args,block)| current.send(*args, &block) end end end end File.read("/etc/passwd").split.sort_by &it.split(":")[2] User.find(:all).map &its.contacts.map(&its.last_name.capitalize)
4,Going crazy
可以让&使用多个参数,更性感。
What I always regretted though was not being to pass any arguments, so I hacked and monkeypatched a bit, and got:
class Symbol def with(*args, &block) @proc_arguments = { :args => args, :block => block } self end def to_proc @proc_arguments ||= {} args = @proc_arguments[:args] || [] block = @proc_arguments[:block] @proc_arguments = nil Proc.new { |obj, *other| obj.send(self, *(other + args), &block) } end end #So you can now write: some_dates.map(&:strftime.with("%d-%M-%Y"))
Not that this is any shorter than just creating the darn block in the first place. But hey, it’s a good exercise in metaprogramming and show of more of Ruby’s awesome flexibility.
After this I remembered something similar that annoyed me before. It’s that Rails helper methods are just a bag of methods available to, because they are mixed in your template. So if you have an array of numbers that you want to format as currency, you’d have to do:
<%= @prices.map { |price| number_to_currency(price) }.to_sentence %>
What if I could apply some to_proc-love to that too? All these helper methods cannot be added to strings, fixnums, and the likes; that would clutter way to much. Rather, it might by a nice idea to use procs that understands helper methods. Here is what I created:
module ProcProxyHelper def it(position = 1) ProcProxy.new(self, position) end class ProcProxy instance_methods.each { |m| undef_method(m) unless m.to_s =~ /^__|respond_to\?|method_missing/ } def initialize(object, position = 1) @object, @position = object, position end def to_proc raise "Please specify a method to be called on the object" unless @delegation Proc.new { |*values| @object.__send__(*@delegation[:args].dup.insert(@position, *values), &@delegation[:block]) } end def method_missing(*args, &block) @delegation = { :args => args, :block => block } self end end end
I used a clean blank class (in Ruby 1.9, you’d want to inherit it from BasicObject), in which I will provide the proper proc-object. I play around with the argument list a bit, handling multiple arguments and blocks too. You can now use this syntax:
<%= @prices.map(&it.number_to_currency).to_sentence %>
That is a lot sexier if you as me. And you can use it in any object, not just inside views. And lets add some extra arguments and some Enumerator-love too:
class SomeClass include ProcProxyHelper def initialize(name, list) @name, @list = name, list end def apply(value, index, seperator) "#{@name}, #{index} #{separator} #{value}" end def applied_list @list.map.with_index(&it.apply(":")) end end
In case you are wondering, the position you can specify is to tell where the arguments need to go. Position 0 is the method name, so you shouldn’t use that, but any other value is okay. An example might be that you cant to wrap an array of texts into span-tags:
<%= some_texts.map(&it(2).content_tag(:span, :class => "foo")).to_sentence %>
So there you have it. I’m probably solving a problem that doesn’t exist. It is however a nice example of the awesome power of Ruby. I hope you’ve enjoyed this little demonstration of the possible uses of to_proc.
最后的一部分来自于http://iain.nl/2010/02/going-crazy-with-to_proc/
发表评论
-
Ruby 搭建环境
2013-06-01 11:17 2066http://kidlet.sinaapp.com/blog/ ... -
ActiveRecord::Dirty
2011-11-21 10:29 793引用Track unsaved attribute chang ... -
Metaprogramming Ruby
2011-09-30 16:11 1197P30 In a sense, the class keywo ... -
RVM Install
2011-09-17 15:17 910http://beginrescueend.com/ -
json
2011-09-15 09:51 844http://flori.github.com/json/ -
Rails计算某月最后一天
2011-08-12 10:46 1464经常忘记这个函数.mark下. 引用end_of_day, e ... -
关于浮点数精度的问题
2011-05-11 15:50 1291在项目里遇到一个很诡异的问题,因为有一些浮点数的计算,总 ... -
Ruby Memoization(转载)
2010-11-28 23:45 829转载http://fuliang.iteye.com/blog ... -
included() vs extended()
2010-11-04 19:48 767# A little helper from _why cl ... -
Nesting Is Different From Inclusion
2010-10-17 10:02 803Nesting Is Different From Inclu ... -
Regular Expressions
2010-10-16 22:55 910... -
ruby里的方法作用域
2010-08-11 09:51 1106在java里private方法在Java当中的含义是只在当前类 ... -
Benchmark
2010-06-17 14:10 9101,length > 0和blank?和emtpy? & ... -
ruby的笔记
2010-05-20 14:23 981最近看了看ruby元编程的一些东西。简单的记下。 1,ruby ... -
闭包(回顾,转载)
2010-03-22 23:02 865闭包的一个重要特征是:过程(方法)内部定义的变量,即使在方法调 ... -
ruby cookbook -- 10.7检查对象是否具有必需的属性
2010-03-01 23:51 791检查是否具有实例变量 class Object de ... -
ruby cookbook -- 10.6. Listening for Changes to a Class监听类的变化
2010-03-01 23:30 791当增加新方法,类方法删除和取消定义的现有方法 class T ... -
ruby cookbook -- 10.4Getting a Reference to a Method(获得方法引用)
2010-03-01 23:25 834A Method object can be stored ... -
irb配置
2010-02-24 13:21 1091#.irbrc require 'rubygems' ... -
ruby cookbook -- 使分配程序能够使用注册回调的返回值
2010-02-23 19:23 796#使分配程序能够使用注册回调的返回值 A simple cha ...
相关推荐
- `Symbol#to_proc`默认禁用:这有助于防止意外的副作用,提高代码的清晰性。 - `Hash#transform_values`方法:这个新方法允许对哈希的所有值进行转换,而不仅仅是键值对。 - 性能改进:Ruby2.7引入了一些优化,如...
3. **方法**:学习如何定义和调用方法,包括块(Block)、Proc和Lambda的区别,以及方法的返回值。 4. **异常处理**:理解Ruby中的异常(Exception)和错误处理,如begin-rescue-end结构。 5. **文件和I/O操作**:...
在Ruby编程语言中,Proc对象是用来封装代码块的类,它允许我们将块(block)作为对象来处理。Proc与块密切相关,可以通过两种方式创建Proc对象:直接使用Proc.new或者通过在方法定义中包含一个块。Proc对象可以调用`...
2. **Symbol to_proc的优化**:Ruby 3.1对`Symbol#to_proc`进行了优化,提高了使用方法引用作为块时的性能。这在处理集合时特别有用,如`array.map(&:method)`。 3. **Ruby编译器改进**:内部编译器的优化使得代码...
Ruby中的块(blocks)和Proc对象也提供了更灵活的代码组织方式。 3. **函数与方法**: 在Ruby中,函数称为方法。你可以定义自己的方法,使用`def`关键字开始,`end`关键字结束。Ruby支持传入参数,并且可以使用...
另一个值得注意的改进是增加了`Symbol#to_proc`的性能。这个特性让符号能够转换为 Proc 对象,从而简化了块的传递。这对于函数式编程风格的Ruby代码来说是个巨大的提升,尤其是在使用`Array#map`、`Array#select`等...
4. `Symbol#to_proc`警告:默认情况下,未使用的`Symbol#to_proc`会触发警告,鼓励开发者检查代码的副作用。 5. 集成了`Ractor`:这是一个实验性的多线程并发模型,旨在提供一种更安全的方式进行并行计算。 在安装...
3. **Symbol to_proc**: 这个版本增强了`Symbol#to_proc`的性能,使得在使用块操作时能更快速地执行。 4. **Proc对象**: 对Proc对象的内存管理进行了优化,降低了内存占用,提高了大型应用的性能。 5. **弃用警告*...
3. **符号到方法转换(Symbol#to_proc)**:Ruby允许将符号转换为块(Proc对象),这样可以更简洁地编写代码。例如,`[:upcase].to_proc.call("hello")`等同于`"hello".upcase`。 4. **模块混合(Mixins)**:Ruby...
5. 符号到方法转换(Symbol to Proc):`&`操作符可以将符号转换为Proc,如`[:upcase].to_proc.call('hello')`将返回'HELLO'。 二、惯用Ruby 1. 使用`tap`方法:`tap`可以在不改变原有对象的情况下,在链式调用中...
5. **Symbol#to_proc (符号到Proc的转换)**:现在,符号可以被转换为一个Proc,进一步增强了函数式编程的能力。 6. **Improved Encoding Support (增强的编码支持)**:Ruby-2.3.3改进了对多种编码格式的支持,使得...
实际上,Block在Ruby中是由`Proc`类表示的,`Proc`类继承自`Object`类: ```ruby empty_block = lambda {} puts empty_block.object_id # 输出 Block的object_id puts empty_block.class # 输出 Proc puts empty_...
** 和 **Proc#to_proc** 的区分:`Proc.new` 创建的 Proc 对象默认是非 lambda 行为,而 `->` 创建的是 lambda 行为。 4. **Hash Destructuring**:在函数调用时可以使用哈希解构,将参数直接映射到变量。 5. **...
Ruby的控制结构是编程逻辑的核心,包括条件语句(如if、unless)、循环(如while、for、each)以及块(Proc和Lambda)。这些结构让开发者能够根据不同的条件执行不同的代码段,或重复执行特定任务。此外,Ruby的异常...
- **语法改进**:Ruby 2.6引入了一些新的语法特性,比如`yield`关键字的简化,以及`Symbol#to_proc`的优化,使代码更易读写。 - **Ruby编译器改进**:Ruby 2.6改进了编译时错误的报告,使调试过程更加友好。 总之...
7. **闭包和 Proc/Lambda**:了解Ruby中的函数对象和它们在代码组织中的作用。 8. **元编程**:Ruby强大的元编程能力,允许在运行时修改和创建类及方法。 这本书不仅仅是一本技术手册,更是一场关于编程哲学和创造...
另外,Ruby还支持块(Blocks)和 Proc 对象,它们可以作为参数传递给方法,实现闭包功能。 **类与继承** Ruby中的类是对象的蓝图,用来创建具有相同属性和行为的对象。类可以通过`class`关键字定义,并可以使用`...
4. **Symbol#to_proc** 的性能提升:这个版本对Symbol#to_proc的实现进行了优化,使其在处理大量迭代时速度更快。 5. 更多的Unicode字符支持:Ruby 2.3.1增强了对Unicode 8.0的支持,包括更多表情符号和特殊字符。 ...
除了 Haskell 过于通用且几乎难以接近的地方,我尝试为日常 Ruby 编程构建一组实际有用的功能工具特征: *注意,请参阅 spec/arrows/proc_spec.rb 以了解如何使用此垃圾功能组合如果给定 x -> F -> y 和 y -> G -> ...
书中可能会介绍`class_eval`、`define_method`等动态创建方法的技术,以及符号到方法的转换(`to_proc`)等高级特性。 4. **Ruby与Rails的集成**:Rails是基于Ruby的Web开发框架,书中可能会详细探讨Ruby如何与...