Shoes wraps it's own Ruby install, right?
I can't use Fiber which is a Ruby1.9 feature. And, I want to use a Fiber for creating a generator.
Here's my code (so you can make sure the problem isn't with my code):
class BrownianGenerator
def initialize
#x = 0
#fiber = Fiber.new do
loop do
#x = #x+rand;
Fiber.yield #x
end
end
end
def next; #fiber.resume end
def rewind; #x=0 end
end
and if I made a shoes app like this:
Shoes.app do
#b = BrownianGenerator.new
end
if I pull up the shoes console, I see the error:
uninitialized constant #<class:0xblah>::BrownianGenerator::Fiber
Since, it's saying Fiber is an uninitialized constant, either something is wrong with my code or this Ruby version doesn't know about the Fiber class - the latter should be the case.
I saw this question on determining the version of Ruby (which is 1.8 for my mac install), but I don't know how I would change the version.
Check out Green Shoes.
It's functionality is based off of _why's original implementation, but it's packaged as a Gem and built specifically for 1.9.
or you could use aman gupta's "poor man's fibers" or try doing ::Fiber
or what not.
GL!
-r
So I jumped into freenode #shoes and found out that the nightly build of shoes is using Ruby1.9. I haven't had time to try building it yet, but that should solve my problem.
Related
We often shorten a block using the & notation on a symbol like this:
some_array.group_by(&:foo)
Is there a similar way to shorten expressions like {|x| x}?
some_array.group_by{|x| x}
If there were a method Object#self that returns self, then we can do
some_array.group_by(&:self)
but unfortunately, there is no such method. In terms of the number of characters, it may be longer, but readability improves.
Yes. #itself was implemented in Ruby 2.2.0.
You can access the Ruby core team discussion about this feature here.
As an interesting analogue, the #ergo method has been proposed, which would yield the receiver to a given block.
If you haven't yet upgraded to Ruby 2.2.0, you may wish to backport #itself and/or define #ergo as follows:
class Object
def itself; self end
def ergo
fail ArgumentError, "Block expected!" unless block_given?
yield self
end
end
And then:
some_array.group_by &:itself
Well, there's no built-in as far as I know, but you can make a reusable identity block:
id = Proc.new {|x| x}
some_array.group_by(&id)
And then if you really wish this were a language feature:
class Object
def it
Proc.new {|x| x}
end
end
And then you can do:
some_array.group_by(&it)
wherever you like. This may void your warranty.
Yes! The method Kernel#itself was added in Ruby 2.2.0. This method simply returns the object it was called on, so you can write:
some_array.group_by(&:itself)
You can see the extensive discussion of this feature here: https://bugs.ruby-lang.org/issues/6373. The patch was submitted by Rafael França in message #53. You can see it in the official Ruby source by looking in object.c.
If you are using a version of Ruby older than 2.2.0, you can easily add Kernel#itself into your project by putting this code somewhere in your project and making sure it gets required:
module Kernel
def itself
self
end
end if !Kernel.instance_methods.include?(:itself)
However, monkey-patching a part of the Ruby core like that can be dangerous and I would not recommend it if you are making reusable code, like a gem. Instead I would recommend just making your own identity function, as suggested by user2246674:
module MyLibrary
IDENT = Proc.new { |x| x }
array.group_by(&IDENT)
end
I have this simple code to generate a lazy array:
lazy_arr = Enumerator.new { |y|
i = 1
loop {
y << i
i+=1
}
}
p lazy_arr.take(5)
In official Ruby 1.9.3, the output is [1,2,3,4,5], which is what I want.
But in Rubinius, it gives error and tells me cannot find Enumerator constant.
So I looked it up, and find Enumerator defined in Enumerable module instead of kernel, and when it is generated, it needs a few arguments in the brackets:
http://rubydoc.info/github/evanphx/rubinius/master/Enumerable/Enumerator
I tried to change Enumerator.new to Enumerable::Enumerator.new, or include Enumerable, neither works because it needs more arguments.
How can I do the example above in Rubinius? Is there any way around to make the code work in both official and Rubinius?
You're using Rubinius in 1.8 mode, which doesn't have Enumerator in the global namespace. Please use Rubinius in 1.9 mode and the example works fine then. You can use 1.9 by passing -X19 when starting Rubinius, or setting RBXOPT=-X19 for example.
It's also possible to make 1.9 mode the default with configure during compile time.
Sounds like a bug/missing class in Rubinius. Open up an issue on github and it will get added. Or dig in and send a pull request!
So in Rails 3.2, ActiveSupport::Memoizable has been deprecated.
The message reads:
DEPRECATION WARNING: ActiveSupport::Memoizable is deprecated and
will be removed in future releases,simply use Ruby memoization
pattern instead.
It refers to "Ruby memoization pattern" (singular) as if there's one pattern we should all know and refer to...
I presume they mean something like:
def my_method
#my_method ||= # ... go get the value
end
or
def my_method
return #my_method if defined?(#my_method)
#my_method = # ... go get the value
end
Is there something else I've missed?
Here is the commit (and subsequent discussion) where Memoizable was deprecated: https://github.com/rails/rails/commit/36253916b0b788d6ded56669d37c96ed05c92c5c
The author advocates the #foo ||= ... approach and points to this commit as an example for migration: https://github.com/rails/rails/commit/f2c0fb32c0dce7f8da0ce446e2d2f0cba5fd44b3.
Edit:
Note that I don't necessarily interpret this change as meaning that all instances of memoize can or should be replaced w/ this pattern. I read it as meaning that Memoizable is no longer needed/wanted in the Rails code itself. As the comments point out, Memoizable is much more than just a wrapper around #foo ||= .... If you need those features, go ahead and use Memoizable, you'll just have to get it from somewhere other than ActiveSupport (I'm guessing someone will fork a gem version, if they haven't already).
Another option is to use the Memoist gem:
Memoist on GitHub
Memoist on RubyGems
It is a direct extraction from ActiveSupport::Memoizable and can be used as a drop-in replacement. Just require 'memoist' and change
extend ActiveSupport::Memoizable
to
extend Memoist
Just an addition to the top answer, to memoize a class method use the following pattern:
class Foo
class << self
def bar
#bar ||= begin
# ...
end
end
end
end
Based upon the comments on the commit referenced above by avaynshtok, I’m going with this:
ActiveSupport::Deprecation.silence { extend ActiveSupport::Memoizable }
… because I figure I’ll know when Memoizable is ripped out of ActiveSupport from my RSpec suite dying right out of the starting gate.
On testing with ruby debugger block_given? gives false but still executes, can someone explain me how its executed?.It is anything related to context(Is debugger changing context)?
if yes then how to find current context.
Now instead of ruby-debug when used pry then block_given? returns true.
def test
debugger
if block_given?
yield(4)
else
puts "ss"
end
end
test {|el| puts "#{el}" }
This looks like a bug in ruby-debug, specifically Kernel#binding_n which is what is getting used by the debugger.
You don't need to go into the debugger read/eval/print loop to see the bug. Here is a non-interactive example example replacing the debugger() call with binding_n(0):
require 'rubygems'; require 'ruby-debug'
Debugger.start
def test
puts eval("block_given?", binding_n(0))
if block_given?
yield(4)
else
puts "ss"
end
end
test {|el| puts "#{el}" }
Pry doesn't have this problem probably because it uses Ruby's binding() rather than binding_n(). Of course that is the most reliable.
In the case above this is clearly a win here since binding() is what is exactly wanted. But as awesome as Pry is, it can't evaluate expressions in any stack frame context except the current (or most recent) stack frame.
See also http://banisterfiend.wordpress.com/2011/01/27/turning-irb-on-its-head-with-pry/#comment-274 for differences between Pry and a debugger such as ruby-debug.
Lastly, I'll note that I tried this both in the patched MRI 1.9.2 trepanning debugger as well as rbx-trepanning for Rubinius 1.2-ish.
Both of them work as expected. In both, the equivalent of binding_n is done differently with more help from the Ruby runtime. That leaves rb8-trepanning which has the bug because it uses binding_n as well.
is there a way in Ruby to find the calling method name inside of a method?
For example:
class Test
def self.foo
Fooz.bar
end
end
class Fooz
def self.bar
# get Test.foo or foo
end
end
puts caller[0]
or perhaps...
puts caller[0][/`.*'/][1..-2]
In Ruby 2.0.0, you can use:
caller_locations(1,1)[0].label
It's much faster than the Ruby 1.8+ solution:
caller[0][/`([^']*)'/, 1]
Will get included in backports when I get the time (or a pull request!).
Use caller_locations(1,1)[0].label (for ruby >= 2.0)
Edit: My answer was saying to use __method__ but I was wrong, it returns the current method name.
I use
caller[0][/`([^']*)'/, 1]
How about
caller[0].split("`").pop.gsub("'", "")
Much cleaner imo.
Instead you can write it as library function and make a call wherever needed. The code goes as follows :
module CallChain
def self.caller_method(depth=1)
parse_caller(caller(depth+1).first).last
end
private
# Copied from ActionMailer
def self.parse_caller(at)
if /^(.+?):(\d+)(?::in `(.*)')?/ =~ at
file = Regexp.last_match[1]
line = Regexp.last_match[2].to_i
method = Regexp.last_match[3]
[file, line, method]
end
end
end
To trigger the above module method you need to call like this:
caller = CallChain.caller_method
code reference from
In order to see the caller and callee information in any language, whether it be ruby or java or python, you would always want to look at the stack trace. In some languages, such as Rust and C++, there are options built into the compiler to turn on some sort of profiling mechanism you can view during run time. I do belive one exists for Ruby called ruby-prof.
And as mentioned above, you could look into the execution stack for ruby. This execution stack is an array containing backtrace location objects.
Essentially all you need to know about this command is as follows:
caller(start=1, length=nil) → array or nil