problems using __next__ method in python - python-2.6

I have just started learning python and am reading about classes .
this is the code i had written for a simple iterable class :
class maths:
def __init__(self,x):
self.a=x
def __iter__(self):
self.b=0
return self
def next(self):
if self.b <= self.a:
self.b = self.b+1
return self.b-1
else:
raise StopIteration
x=maths(5)
for l in x:
print l
for the next() method when i used the __next__(self):
the following error was displayed
Traceback (most recent call last):
File "class.py", line 20, in <module>
for l in x:
TypeError: instance has no next() method
Can anyone elucidate on this behaviour . i saw an example in the dive into python 3 book by Mark Pilgrim that used the __next__ method . even the example did not run on my interpreter .
Thanks for taking your time off to help me !

You're using Python 2.x, which has used .next() since forever and still does so - only Python 3 renamed that method to .__next__(). Python 2 and 3 aren't compatible. If you're reading a 3.x book, use Python 3.x yourself, and vice versa.
For Python 2.x, you can change __next__() to next()

Related

How to calling a function with arguments in one .rb script to another .rb script

I am new to Ruby language. i want to work with ruby language, i have installed ruby 2.1.5 and i am trying to calling one .rb script to another .rb script with arguements and can you please suggest me how to do this.
i have written following code
b.rb
require_relative 'a'
def hello($a,$b,$c)
$d=$a+$b+$c
print "d value is :"+$d
end
a.rb
def sample
$a=1
$b=3
$c=4
$str="hello"
eval"&$str($a,$b,$c)"
end
i am getting nothing from this script can you please suggest me...
You need to change code to this -
a.rb:
require_relative 'b'
def sample
$a = 1
$b = 3
$c = 4
$str = "hello"
eval "#{$str}(#{$a},#{$b},#{$c})"
end
sample
b.rb:
def hello(a, b, c)
d = a + b +c
print "d value is : " + d.to_s
end
Now, go to the directory where these files are present in your terminal and run the following:
$ ruby a.rb
#=> d value is : 8
Few things I'd like to point out that you missed here:
You need to require b.rb inside a.rb since you're using method from b.rb and not vice a versa.
Ruby does not allow to define global variables as parameters in a method definition. So, in method hello you'd need to (a, b, c), not ($a, $b, $c).
You can not concatenate a string with an integer: "d value is :"+$d it has to be a string: "d value is :" + d.to_s.
Please refrain from creating global variables and using them in different places of your code, unless you're doing this for learning and experimentations.
Please indent your code by two white spaces for better reading experience, it will help you or someone else in future when you or the developer has to go back to your old code to fix or add a new functionality.
That's a pretty confusing little bit of code. A simple thing that may get it working is to require b from a instead of what you are currently doing requiring a from b. Also, you need to call sample after you have defined it.
To call the sample function just write "sample" on a line beneath end in b.rb

ruby 2.0 how to access element in matrix by coordinate?

I'm new to ruby, but here is the problem. Say I have a matrix, and I need to modify a element at 1,2
mm = Matrix.build(2,4) {0}
mm[1][2] = 404
but this will rise error message
ArgumentError: wrong number of arguments (1 for 2)
from /Users/xxxxxx/.rvm/rubies/ruby-2.0.0-p0/lib/ruby/2.0.0/matrix.rb:314:in `[]'
from (irb):11
from /Users/xxxxxx/.rvm/rubies/ruby-2.0.0-p0/bin/irb:16:in `<main>'
I have checked ruby doc, but didn't find any answer, sorry to ask such a stupid question...
Get element:
mm[1,2] #output 0
Set element:
No method can do that. Matrix is immutable object and cannot be changed (which is, IMHO, not so optimal). You can either copy the matrix by each to an array, change the element, and convert back, or use monkey patch
class Matrix
def []=(i, j, x)
#rows[i][j] = x
end
end
mm[1,2] = 404
Or if you don't want to monkey patch or want to be a bit hacky (although does not look good):
mm.send(:[]=, 1, 2, 404)

use the correct number of arguments for new in Ruby

I am working on a gem that can uses different version of Gherkin, but I'm facing a problem:
in the 2.4.0 version Gherkin::Formatter::Model::Scenario.new takes 6 arguments but in 2.6.5 it takes 7 arguments.
So my question is what is a best practice in this case ? Should I do:
case Gherkin::Version
when '2.4.0'
do the init with 6 arguments
else
with the 7
end
I was thinking also of creating a new_with_arity method:
class Object
def new_with_arity(*params)
puts method(:initialize).arity # => -1
puts method(:new).arity # => -1
new(*(params + [nil] * (params.count - method(:new).arity)))
end
end
However this does not work, the arity of new and initialize is -1.
Do you have an idea ?
I would recommend following Jim Deville's advice. Saying that it's quite an interesting idea and you were pretty close. The problem is you can't get the method without having an instance, so the trick is to use allocate first.
class Object
def new_with_arity(*params)
new *(params + [nil] * (allocate.method(:initialize).arity - params.size))
end
end
class One
def initialize a
[a]
end
end
class Two
def initialize a, b
[a, b]
end
end
One.new_with_arity 1 #=> [1]
Two.new_with_arity 1, 2 #=> [1, 2]
Two.new_with_arity 1 #=> [1, nil]
I would build 2 Gherkin adapters and load up the proper one for the proper version. Or, you are using Rubygems, so you can force a specific version of the Gherkin parser

Any way to determine which object called a method?

I'm hoping that Ruby's message-passing infrastructure means there might be some clever trick for this.
How do I determine the calling object -- which object called the method I'm currently in?
You can easily look at the line of code that called the function of interest through
caller.first
which will tell you the filename and line number which called the relevant function. You could then back-calculate which object it was.
However, it sounds like you're more after some object that called a certain function, perhaps within an instance method. I'm not aware of a method for figuring this out - but I wouldn't use it anyway, since it seems to violate encapsulation badly.
As an option, there is a binding_of_caller gem that allows you to execute code in context of any caller on the call stack (caller, caller's caller and so on). It's useful for inspecting (read do anything at any position on the call stack) call stack in development, as used in better_errors.
Objects of class Binding encapsulate the execution context at some particular place in the code and retain this context for future use.
– http://www.ruby-doc.org/core-2.1.4/Binding.html
Should I mention, this technique should only be used for debugging, fun or educational purposes, because it violates principles of OOP really badly.
Mostly because of eval.
Let's prepare stuff:
require 'binding_of_caller' # I assume, you installed this gem already?
Get the immediate (closest on stack, hence 0) caller instance:
binding.of_caller(0).eval('self')
...or even an immediate calling method:
binding.of_caller(0).eval('__method__')
If you need to get higher up the call stack, use numbers other than 0 for getting a caller's binding.
Awfully hacky. But if you really need this — there you go.
Technology at its finest:
1 # phone.rb
2 class Phone
3 def caller_id
4 caller
5 end
6 end
7
8 class RecklessDriver
9 def initialize
10 #phone = Phone.new
11 end
12 def dial
13 #phone.caller_id
14 end
15 end
16
17 p = Phone.new
18 p.caller_id.inspect # => ["phone.rb:18:in `<main>'"]
19
20 macek = RecklessDriver.new
22 macek.dial.inspect # => ["phone.rb:13:in `dial'", "phone.rb:22:in `<main>'"]
Note: Line number for demonstrative purposes. phone.rb:X refers to Line X of the script.
Look at phone.rb:13! This dial method is what sent the call! And phone.rb:22 refers to the reckless driver that used the dial method!
You mean like self?
irb> class Object
.. def test
.. self
.. end
.. end
=> nil
irb> o = Object.new
=> #<Object:0xb76c5b6c>
irb> o.test
=> #<Object:0xb76c5b6c>
Peter's answer used in production code example
In my company we were deprecating deleted flag in flavor of Paranoia gem deleted_at column. The code bellow is how we were ensuring all will go well before we remove column (deploying this code and then after 2 or 3 days of being live we deploy migration remoove_column :lessons, :deleted
class Lesson < ActiveRecord::Base
def deleted
if caller.select { |c| c.match /serialization\.rb/ }.any?
# this is Rails object mapping
!!deleted_at
else
raise 'deplicated - deleted was replaced by deleted_at'
end
end
end

How can I get source and variable values in ruby tracebacks?

Here's the last few frames of a typical Ruby on Rails traceback:
And here are the last few frames of a typical Nevow traceback in Python:
It's not just the web environment either, you can make similar comparisons between ipython and irb. How can I get more of these sorts of details in Ruby?
AFAIK, once an exception has been caught it's too late to grab the context in which it was raised. If you trap the exception's new call, you could use evil.rb's Binding.of_caller to grab the calling scope, and do
eval("local_variables.collect { |l| [l, eval(l)] }", Binding.of_caller)
But that's quite a big hack. The right answer is probably to extend Ruby to allow some inspection of the call stack. I'm not sure if some of the new Ruby implementations will allow this, but I do remember a backlash against Binding.of_caller because it will make optimizations much harder.
(To be honest, I don't understand this backlash: as long as the interpreter records enough information about the optimizations performed, Binding.of_caller should be able to work, although perhaps slowly.)
Update
Ok, I figured it out. Longish code follows:
class Foo < Exception
attr_reader :call_binding
def initialize
# Find the calling location
expected_file, expected_line = caller(1).first.split(':')[0,2]
expected_line = expected_line.to_i
return_count = 5 # If we see more than 5 returns, stop tracing
# Start tracing until we see our caller.
set_trace_func(proc do |event, file, line, id, binding, kls|
if file == expected_file && line == expected_line
# Found it: Save the binding and stop tracing
#call_binding = binding
set_trace_func(nil)
end
if event == :return
# Seen too many returns, give up. :-(
set_trace_func(nil) if (return_count -= 1) <= 0
end
end)
end
end
class Hello
def a
x = 10
y = 20
raise Foo
end
end
class World
def b
Hello.new.a
end
end
begin World.new.b
rescue Foo => e
b = e.call_binding
puts eval("local_variables.collect {|l| [l, eval(l)]}", b).inspect
end

Resources