This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What does map(&:name) mean in Ruby?
I was watching a railscast and saw this code.
[Category, Product].(&:delete_all)
In regards to clearing a database.
I asked about the line in IRC and was told
(&:delete_all)
was a shortcut for
{|model| model.delete_all}
I tested this with the following
class ClassOne
def class_method
puts 1
end
end
class ClassTwo
def class_method
puts 2
end
end
[ClassOne, ClassTwo].each(&:class_method)
I received an error saying
Wrong Argument type Symbol (expected Proc)
I also tried
one = ClassOne.new
two = ClassTwo.new
[one, two].each(&:class_method)
But that still failed.
If I modified it to read
[one, two].each{|model| model.class_method}
Everything worked as expected.
So, what does &:delete_all actually do? The docs say delete_all is a method, so I am confused as to what is going on here.
This relies upon a Ruby 1.9 extension that can be done in 1.8 by including the following:
class Symbol
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
end
I believe Rails defines this in ActiveSupport.
It's some Rails specific patching of Ruby, symbol to proc.
Related
This question already has an answer here:
Ruby, no implicit conversion of Symbol into Integer
(1 answer)
Closed 6 years ago.
I am new to ruby, and have no idea, how to fix this error. when i run my script containing the code below, i always get the error: 'no implicit conversion of Symbol into Integer. I think the Problem is in the lines #killProc..., #Name=..., and #working_directory.
Can you tell me whats wrong?
Thanks for your help
class RubyCommand
include Patir::Command
attr_reader :cmd,:working_directory,:killProc
def initialize params,&block
#killProc=params[:killProc]
#name=params[:name]
#working_directory=params[working_directory]||"."
if block_given?
#cmd=block
else
raise "You Need to provide a block"
end
end
end
Pretty sure you're passing an array instead of a hash. You should call it like this:
RubyCommand.new({killProc:1,name:"test"})
This question already has answers here:
When to use lambda, when to use Proc.new?
(14 answers)
Closed 8 years ago.
I am new to ruby, and while learning it I didn't understand the concept of lambdas or procs. I know lambda and proc are the blocks of code that have been bound to a set of local variables. But I don't understand their use.
So
what advantage does a programmer get from it?
I had asked this question in past and got marked as duplicate and was given a link that had totally unrelated answered so please before marking it as duplicate or scolding me please view the answers of other links by yourself first.
This is a broad question. You're basically asking "why are closures important?". Two uses that come to mind for me are:
DISCLAIMER: I haven't actually run any of this code, but it should get the point across.
Delayed execution of code. If I want to pass some code as a callback (e.g. Rails' after_create), I can use a closure to "hook" into Rails by passing a block. That block has the context of the current class, but it doesn't need to get run until Rails says so.
class SuperClass
def self.after_create(&block)
#__after_create = block
end
def self.create
# do normal create logic
instance = self.new
if #__after_create
#__after_create.call(instance)
end
end
end
class MyClass < SuperClass
after_create {|instance| instance.log}
def log
puts 'hello world!'
end
end
MyClass.create
Passing functions as parameters. This makes it easier to do things like write a generic tree traversal algorithm that just passes each node of the tree to some function:
def Tree.elements
["hello", "world!"]
end
def Tree.traverse(&block)
elements.each {|el| block.call(el)}
end
Tree.traverse {|el| puts el} # "hello" "world!"
Tree.traverse {|el| puts el.size} # "5" "6"
This question already has answers here:
Can you supply arguments to the map(&:method) syntax in Ruby?
(9 answers)
Closed 8 years ago.
I wonder, isn't it possible to call a method using & operator with parameters?
items.each &:my_proc # ok
items.each &:my_proc(123, "456") # ops!
No, it's not possible. Use full form.
items.each{|i| i.my_proc(123, '456')}
Look at the source of Symbol#to_proc for the "why".
You can use a bit of trickery and acheive something similar:
class Symbol
def [](*args)
proc{|obj| obj.send(self, *args) }
end
end
[123.456, 234.567].map(&:round[2])
#=> [123.46, 234.57]
I highly discourage the use in production code though, since gems etc may rely on Symbol#[]. This is just a fun thing to play around with ;-)
This question already has an answer here:
Notification of object destruction in Ruby
(1 answer)
Closed 9 years ago.
I'm using RubyPython to import a Python module. I am doing RubyPython.start in the constructor (initialize), and I suppose I should symmetrically do RubyPython.stop in the destructor, but unfortunately it seems that there is no destructor in Ruby:
class QDSHiveHelper
def initialize
RubyPython.start
qds = RubyPython.import('blah')
...
end
def do_something
qds.some_function
...
end
def finalize
RubyPython.stop
end
end
Could someone please explain how to accomplish this? ObjectSpace.define_finalize seems to be discouraged and has some gotchas (can't use closure etc). I could also just leave RubyPython dangling and not call stop on it, but I don't know what could be the consequences. What's the best way out?
There is a hook called ObjectSpace.define_finalizer that is called when an object is destroyed.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Ruby functions vs methods
Im just reading some ruby documentation and t seems to use the term function and method in an interchangeable way, i jut wanted to know if there is any distinction?
the docs im looking at refer to this as a function:
def saysomething()
puts "Hello"
end
saysomething
and this a method:
def multiply(val1, val2 )
result = val1 * val2
puts result
end
this may be a something semantic but i wanted to check
jt
In Ruby, there are not two separate concepts of methods and functions. Some people still use both terms, but in my opinion, using "function" when talking about Ruby is incorrect. There do not exist executable pieces of code that are not defined on objects, because there is nothing in Ruby that is not an object.
As Dan pointed out, there's a way to call methods that makes them look like functions, but the underlying thing is still a method. You can actually see this for yourself in IRB with the method method.
> def zomg; puts "hi"; end
#=> nil
> method(:zomg)
#=> #<Method: Object#zomg>
> Object.private_instance_methods.sort
#=> [..., :zomg]
# the rest of the list omitted for brevity
So you can see, the method zomg is an instance method on Object, and is included in Object's list of private instance methods.