Newbie Question. eval.rb variable scope issue

ruby

    Sponsored Links

    Next

  • 1. downloading a file
    hello what is the best way to download a file? if the process get interrupted like the network goes down for a little while, is there a way to continue the download from the point it left off? I am seeking various solutions, thanks! -- Kind Regards, Rajinder Yadav | DevMentor.org | Do Good! ~ Share Freely GNU/Linux: 2.6.35-23-generic Kubuntu x86_64 10.10 | KDE 4.5.1 Ruby 1.9.2p0 | Rails 3.0.3

Re: Newbie Question. eval.rb variable scope issue

Postby Bill Kelly » Mon, 02 Jul 2007 16:29:57 GMT

From: "Rishel,Wes" < XXXX@XXXXX.COM >

Welcome !

I don't know the exact reason, but it seems you'll need to
obtain a binding context from outside the iterator block.
E.g.

  a = ['word = 2', 'word']
  b = binding
  a.each {|line| p( eval(line, b) ) }


Incidentally, have you found `irb` yet?  There should be an irb.bat
in the bin directory next to your ruby.exe.  IRB is "interactive
ruby", similar to invoking python with no arguments.

A couple tips:

  p(expr) is a shortcut for puts(expr.inspect)

So,

  print eval(line).inspect, "\n"

can be written as:

  p line

Also, puts is like print, but adds the "\n" for you.
So,

  print line + "\n"

can be:

  puts line



Hope this helps,

Regards,

Bill

  


Re: Newbie Question. eval.rb variable scope issue

Postby Marc Heiler » Mon, 02 Jul 2007 18:41:08 GMT

If you installed cygwin (+bash) just alias irb to the /ruby/irb.bat or 
wherever it resides. In irb you can really dump-test ruby code quickly.

"who got interested in Rails an decided to check out
Ruby."

I think you should give ruby a good chance, so to understand it.
Often people that use rails end up learning ruby (at least understanding 
the syntax things), and IMHO its better to know how the core concepts of 
ruby work, how to write your own classes, modules methods etc..


Btw instead of
  print line + "\n"   # WJR change
you could just do
  puts line

-- 
Posted via  http://www.**--****.com/ 


Re: Newbie Question. eval.rb variable scope issue

Postby Robert Dober » Mon, 02 Jul 2007 19:27:20 GMT



Welcome to the jewel.
Local variables spring into existance in the scope they are assigned to
Our friend irb shows this quite nicely

irb(main):008:0> %w{ word=2 word }.each{|c| p eval( c )}
2
NameError: undefined local variable or method `word' for main:Object
        from (irb):8
        from (irb):8:in `eval'
        from (irb):8
        from (irb):8:in `each'
        from (irb):8
        from :0
irb(main):009:0> word=nil
=> nil
irb(main):010:0> %w{ word=2 word }.each{|c| p eval( c )}
2
2
=> ["word=2", "word"]

eval creates a scope of it's own, thus eval("word=2") brings it into
life and it sadly dies.
But when eval("word=2") assigns to the already existing local variable
in the outer scope it persists into the next eval.

And just a friendly hint, forget eval you *do not need it* :).

HTH
Robert

-- 
I always knew that one day Smalltalk would replace Java.
I just didn't know it would be called Ruby
-- Kent Beck


Re: Newbie Question. eval.rb variable scope issue

Postby Rishel,Wes » Tue, 03 Jul 2007 00:12:54 GMT

Thanks, Bill. It sounds like irb will fill my needs. 

I have to say that featuring eval in the tutorials when it doesn't work
for a simple set of interactions like setting a variable and then
printing it seems very newbie unfriendly.

Some languages have a culture that excludes all but the smartest and
those who are willing to devote all their time to memorizing the
nuances. I would put Perl in that category. The initial "affect" of the
Ruby language and community is else-wise, but a couple of things make me
wonder. This includes tutorials that don't work in every case and the
fact that there is no free version of documentation for the current
version, which was released > 3 months ago.

If it weren't for people like you willing to respond it could be very
off-putting indeed.


-----Original Message-----
From: Bill Kelly [mailto: XXXX@XXXXX.COM ] 
Sent: Sunday, July 01, 2007 12:30 AM
To: ruby-talk ML
Subject: Re: Newbie Question. eval.rb variable scope issue

From: "Rishel,Wes" < XXXX@XXXXX.COM >
out
created

Welcome !

I don't know the exact reason, but it seems you'll need to
obtain a binding context from outside the iterator block.
E.g.

  a = ['word = 2', 'word']
  b = binding
  a.each {|line| p( eval(line, b) ) }


Incidentally, have you found `irb` yet?  There should be an irb.bat
in the bin directory next to your ruby.exe.  IRB is "interactive
ruby", similar to invoking python with no arguments.

A couple tips:

  p(expr) is a shortcut for puts(expr.inspect)

So,

  print eval(line).inspect, "\n"

can be written as:

  p line

Also, puts is like print, but adds the "\n" for you.
So,

  print line + "\n"

can be:

  puts line



Hope this helps,

Regards,

Bill

  

This e-mail message, including any attachments, is for the sole use of the person to whom it has been sent, and may contain information that is confidential or legally protected. If you are not the intended recipient or have received this message in error, you are not authorized to copy, distribute, or otherwise use this message or its attachments. Please notify the sender immediately by return e-mail and permanently delete this message and any attachments.  Gartner makes no warranty that this e-mail is error or virus free. 


Re: Newbie Question. eval.rb variable scope issue

Postby Rishel,Wes » Tue, 03 Jul 2007 00:20:56 GMT

Thanks, Marc. I will try that.

BTW, I agree with your other advice. I won't start to try Rails until I
feel reasonably competent at writing OO code in Ruby. 

-----Original Message-----
From:  XXXX@XXXXX.COM  [mailto: XXXX@XXXXX.COM ] On Behalf
Of Marc Heiler
Sent: Sunday, July 01, 2007 2:41 AM
To: ruby-talk ML
Subject: Re: Newbie Question. eval.rb variable scope issue

If you installed cygwin (+bash) just alias irb to the /ruby/irb.bat or 
wherever it resides. In irb you can really dump-test ruby code quickly.

"who got interested in Rails an decided to check out
Ruby."

I think you should give ruby a good chance, so to understand it.
Often people that use rails end up learning ruby (at least understanding

the syntax things), and IMHO its better to know how the core concepts of

ruby work, how to write your own classes, modules methods etc..


Btw instead of
  print line + "\n"   # WJR change
you could just do
  puts line

-- 
Posted via  http://www.**--****.com/ 

This e-mail message, including any attachments, is for the sole use of the person to whom it has been sent, and may contain information that is confidential or legally protected. If you are not the intended recipient or have received this message in error, you are not authorized to copy, distribute, or otherwise use this message or its attachments. Please notify the sender immediately by return e-mail and permanently delete this message and any attachments.  Gartner makes no warranty that this e-mail is error or virus free. 


Re: Newbie Question. eval.rb variable scope issue

Postby Chris Carter » Tue, 03 Jul 2007 00:40:27 GMT



I would like to know which tutorial out there you were following that
teaches use of eval().  The Ruby Way generally does not recommend the
use of eval with a string unless you are doing some  very advanced
work, and even then it is very risky business.

Ruby does have it's nuances, but this community, as you can see, is
quite willing to help you out when you have found one, and help you
figure out what it is and why it is.  I don't know which tutorial you
are referring to, because none of the "official" tutorials on the
ruby-lang.org website mention eval.  If you want a good place to start
learning ruby, I suggest you check out _why's poignant guide to ruby
( http://www.**--****.com/ ), it is a little wacky, but it teaches
the language and the concepts of the ruby way very well.

As to no free documentation for the most recent version of ruby, one
ships with your ruby install (the ri tool and the rdocs) and there is
ruby-doc.org.

Welcome to Ruby, if you hit any other major problems feel free to ask.
 We also have a lively IRC channel #ruby-lang on freenode.  Hope you
like the language. And be aware, the philosophy guiding Ruby is not
the same as that of python's.


-- 
Chris Carter
concentrationstudios.com
brynmawrcs.com


Re: Newbie Question. eval.rb variable scope issue

Postby Robert Dober » Tue, 03 Jul 2007 03:01:02 GMT


Well as I showed above it works if this is unclear from the tutorial
than this is indeed bad a tutorial, maybe you would care to provide us
with a link?
Maybe you rather want to have a look at this
 http://www.**--****.com/ 
But I am not sure I can follow your vision, we are quite aware that
the documentation of Ruby is not top - but there is great stuff out
there, like mentioned above.
That said I do not think eval does not work, at least the behavior you
have described is completely normal.
Eval is not the point where to start and if someone starts at the
toughest spot she will realize err that she started at the toughest
spot.

It might not be the best approach to learn Ruby by criticizing as you
do, not that someone will care too much, you are just losing your
time.


This is maybe the second time I have heard this complaint in this
list; after two years of reading it, but we are all different and if
you feel so, sorry.

Cheers
Robert

-- 
I always knew that one day Smalltalk would replace Java.
I just didn't know it would be called Ruby
-- Kent Beck


Re: Newbie Question. eval.rb variable scope issue

Postby Rishel,Wes » Tue, 03 Jul 2007 03:13:40 GMT

obert,

I have said repeatedly that I am not (a) expressing direct opinions on
Ruby -- the language, or (b) attempting to compare it to Python.

In another posting I provided the URL to what appears to be the prime
tutorial on Ruby, at least it is featured in a set of links delivered
with the software. Simple examples don't work.

If I dared to comment that this might be off-putting to the newbie then
I guess whether that is hostile or not depends a lot on the culture of
the community. I have certainly been careful to avoid being accusatory,
sarcastic and to keep the "tone" of my emails emotionally neutral. To me
this seems like the courteous thing to do.

So far I have given examples that don't work in the tutorial that is
recommended in the software distribution, and asked questions to help me
understand why the Ruby approach to local variable scoping is meant to
work the way it does.

Apparently you feel that this is hostile. All I can hope is that others
in the community are more open to discussion that is collegial.

If most people on the list feel I am not being collegial then I will try
to figure out why. Usually I have good luck at keeping the discussion
focused on issues.

-----Original Message-----
From: Robert Dober [mailto: XXXX@XXXXX.COM ]
Sent: Sunday, July 01, 2007 11:01 AM
To: ruby-talk ML
Subject: Re: Newbie Question. eval.rb variable scope issue

On 7/1/07, Rishel,Wes < XXXX@XXXXX.COM > wrote:
work
Well as I showed above it works if this is unclear from the tutorial
than this is indeed bad a tutorial, maybe you would care to provide us
with a link?
Maybe you rather want to have a look at this
http://www.ruby-doc.org/docs/ProgrammingRuby/
the
me
But I am not sure I can follow your vision, we are quite aware that
the documentation of Ruby is not top - but there is great stuff out
there, like mentioned above.
That said I do not think eval does not work, at least the behavior you
have described is completely normal.
Eval is not the point where to start and if someone starts at the
toughest spot she will realize err that she started at the toughest
spot.

It might not be the best approach to learn Ruby by criticizing as you
do, not that someone will care too much, you are just losing your
time.


This is maybe the second time I have heard this complaint in this
list; after two years of reading it, but we are all different and if
you feel so, sorry.

Cheers
Robert

--
I always knew that one day Smalltalk would replace Java.
I just didn't know it would be called Ruby
-- Kent Beck

This e-mail message, including any attachments, is for the sole use of the person to whom it has been sent, and may contain information that is confidential or legally protected. If you are not the intended recipient or have received this message in error, you are not authorized to copy, distribute, or otherwise use this message or its attachments. Please notify the sender immediately by return e-mail and permanently delete this message and any attachments. Gartner makes no warranty that this e-mail is error or virus free.


Re: Newbie Question. eval.rb variable scope issue

Postby Stefano Crocco » Tue, 03 Jul 2007 03:38:59 GMT

Alle domenica 1 luglio 2007, Rishel,Wes ha scritto:

I don't know why you're getting this behaviour. On my system (linux, ruby 
1.8.6 p36), the example works correctly:

ruby> var = " abc "
   " abc "
ruby> "1234#{var}5678"
   "1234 abc 5678"


Here, I think you're wrong. The Pickaxe first edition states it clearly in 
the "Expressions" chapter (section "Variable scope and loops"):
"The while, until, and for loops are built into the language and do not 
introduce new scope; previously existing locals can be used in the loop, and 
any new locals created will be available afterward."
This is different from what happens with blocks, where variables created 
inside the block aren't accessible outside them. Since eval.rb uses a while 
loop, instead, variables defined in one iteration are kept in the following.

Stefano


Re: Newbie Question. eval.rb variable scope issue

Postby Stefano Crocco » Tue, 03 Jul 2007 03:44:37 GMT

Alle domenica 1 luglio 2007, Stefano Crocco ha scritto:

Now I know. I was using the eval.rb script provided on the tutorial website, 
while you are using the one provided with the ruby distribution.

Stefano


Re: Newbie Question. eval.rb variable scope issue

Postby Rishel,Wes » Tue, 03 Jul 2007 03:48:31 GMT

It is reassuring to know that the problem is a local problem. I hope someone will be able to help me understand why it might be happing. Perhaps someone on Windows could try the example and see if it's an issue with the distribution package?

In believing that the example failing was consistent with what was written in the same tutorial later on. It states

The first assignment you make to a local variable acts something like a declaration. If you refer to an uninitialized local variable, the ruby interpreter thinks of it as an attempt to invoke a method of that name; hence the error message you see above.

Generally, the scope of a local variable is one of

	proc{ ... } 
	*** loop{ ... } *** (my emphasis)
	def ... end 
	class ... end 
	module ... end 
	the entire program (unless one of the above applies)

There are further examples in the tutorial that support my interpretation:

	ruby> foo = 44; print foo, "\n"; defined? foo
	44
	   "local-variable"
	ruby> loop{bar=45; print bar, "\n"; break}; defined? bar
	45
	   nil

I must be missing something. 

-----Original Message-----
From: Stefano Crocco [mailto: XXXX@XXXXX.COM ] 
Sent: Sunday, July 01, 2007 11:39 AM
To: ruby-talk ML
Subject: Re: Newbie Question. eval.rb variable scope issue

Alle domenica 1 luglio 2007, Rishel,Wes ha scritto:

I don't know why you're getting this behaviour. On my system (linux, ruby 
1.8.6 p36), the example works correctly:

ruby> var = " abc "
   " abc "
ruby> "1234#{var}5678"
   "1234 abc 5678"


Here, I think you're wrong. The Pickaxe first edition states it clearly in 
the "Expressions" chapter (section "Variable scope and loops"):
"The while, until, and for loops are built into the language and do not 
introduce new scope; previously existing locals can be used in the loop, and 
any new locals created will be available afterward."
This is different from what happens with blocks, where variables created 
inside the block aren't accessible outside them. Since eval.rb uses a while 
loop, instead, variables defined in one iteration are kept in the following.

Stefano

This e-mail message, including any attachments, is for the sole use of the person to whom it has been sent, and may contain information that is confidential or legally protected. If you are not the intended recipient or have received this message in error, you are not authorized to copy, distribute, or otherwise use this message or its attachments. Please notify the sender immediately by return e-mail and permanently delete this message and any attachments.  Gartner makes no warranty that this e-mail is error or virus free. 


Re: Newbie Question. eval.rb variable scope issue

Postby Stefano Crocco » Tue, 03 Jul 2007 04:09:43 GMT

Alle domenica 1 luglio 2007, Rishel,Wes ha scritto:

It's not a local problem. As I said in my second message, there are two files 
called eval.rb involved in this problem. One is included in the ruby 
distribution, is the one you're using and doesn't allow to run the code in 
the tutorial; the other is the one in the tutorial website 
( http://www.**--****.com/ ), which is the one I 
used, which works correctly. The latter, as the tutorial itself says, is more 
advanced, but the main difference is that it uses 'while', while the other 
uses 'loop'. Since 'loop' introduces a new scope, variables defined in one 
iteration are lost in the next - so the bug. 'while' doesn't introduce a new 
scope, so the program works.


You're mostly right here. proc and loop are instance methods of the Kernel 
module, so they don't create a new scope. What happens is that you pass these 
methods a block, and it is the block which introduces a new scope (the same 
happens for every method which accepts a block).

I hope this helps

Stefano


Re: Newbie Question. eval.rb variable scope issue

Postby Rishel,Wes » Tue, 03 Jul 2007 04:18:45 GMT

Stefano, mil grazie!

I don't know how to pass a suggestion to those who maintain the library, but it would be a one-line change to make the "simple" one use while 1 instead of loop do.





-----Original Message-----
From: Stefano Crocco [mailto: XXXX@XXXXX.COM ] 
Sent: Sunday, July 01, 2007 12:10 PM
To: ruby-talk ML
Subject: Re: Newbie Question. eval.rb variable scope issue

Alle domenica 1 luglio 2007, Rishel,Wes ha scritto:

It's not a local problem. As I said in my second message, there are two files 
called eval.rb involved in this problem. One is included in the ruby 
distribution, is the one you're using and doesn't allow to run the code in 
the tutorial; the other is the one in the tutorial website 
( http://www.**--****.com/ ), which is the one I 
used, which works correctly. The latter, as the tutorial itself says, is more 
advanced, but the main difference is that it uses 'while', while the other 
uses 'loop'. Since 'loop' introduces a new scope, variables defined in one 
iteration are lost in the next - so the bug. 'while' doesn't introduce a new 
scope, so the program works.


You're mostly right here. proc and loop are instance methods of the Kernel 
module, so they don't create a new scope. What happens is that you pass these 
methods a block, and it is the block which introduces a new scope (the same 
happens for every method which accepts a block).

I hope this helps

Stefano

This e-mail message, including any attachments, is for the sole use of the person to whom it has been sent, and may contain information that is confidential or legally protected. If you are not the intended recipient or have received this message in error, you are not authorized to copy, distribute, or otherwise use this message or its attachments. Please notify the sender immediately by return e-mail and permanently delete this message and any attachments.  Gartner makes no warranty that this e-mail is error or virus free. 


Re: Newbie Question. eval.rb variable scope issue

Postby Robert Dober » Tue, 03 Jul 2007 04:36:33 GMT


Please do not top post.

No I do not at all.
What issue? Eval, local scopes or an error in a Tutorial you do not link to?
Funny I just got the feeling that you are worried about writing
speeches, well if I could not help than I could not help, no problem
at all.

Robert
-- 
I always knew that one day Smalltalk would replace Java.
I just didn't know it would be called Ruby
-- Kent Beck


Similar Threads:

1.newbie question about scope, variables, declarations of variables and option strict (as in perl)


Hello,

I am trying to understand the syntax error I receive in a code similar to
this.

1 require 'logger'
2
3 log = logger.new  #some other logger settings are ignored.

4 def func
5   log.debug "a statement" # error is reported here when func is called
below
6  # some code
7 end
8
9 #some code continues
10 func


When func is called, an error is reported on line-5 saying that undefine
local variable log etc. I understand that functions create scopes and log is
seen as local variable  which is not defined in that scope. As it is
qualified with no scope operator, interpreter thinks that it is local but
can not find definition of the log before it's usage but also in the
parameter list and I understand that. On the other hand, I can use log
without qualifying it with a scope symbol anywhere in the same file if it is
not in a function. I know that loops, if statements etc are built into the
language and do not create scope. Code blocks inherit the locals. So it is
meaningful that I can use it anywhere else. When I qualify log with $ as
$log, it becomes global and I no longer receive error. I have tried it
qualifying with @ etc. but the received the same error. What I am asking is,
what is scope of log?. What kind of variable is it? It is the local or
instance variable of what, Object? I know that func is private to the
Object. But what about log?  How  can  I  access it in a function without
making it global?

Is there a way to make variables local to a file as perl does with "my".

Is there a strict option that prevents unintended variable creation because
of typos. Is there a way force predeclaration of variables?

Thanks.

2.Newbie question re. blocks & variable scope

Hi,

I'd like to ask for some help with local variable scope.  I understand
that the scope of a local variable is the "do...end" block in which it
is created.  However, the code below shows that the value assigned to
the variable within a block does not persist after the single
iteration in which the variable is given that value, although the
variable is still defined in a later iteration. That is, in the idx=2
iteration, Ruby does not remember that a=11 in the previous iteration,
but it also does not complain about an undefined local variable "a"
(which it of course does outside the block). I haven't been able to
find this behavior mentioned in the documentation or in this
group--can you point me to something that will clarify for me what is
going on?

Thanks,
Steve

data=[1,2]
data.each do | idx|
	if idx == 1
		a = 11
		print "idx=1: a=",a,"\n"
	elsif idx == 2
		b = 12
		print "idx=2: a=",a," b=",b,"\n"
	end
end
print "after:\n"
print "a=",a," b=",b,"\n"
	
>c:\ruby\bin\ruby test.rb
idx=1: a=11
idx=2: a=nil b=12
after:
test.rb:12: undefined local variable or method `a' for main:Object
(NameError)
>Exit code: 1

3.newbie scope issue

I'm brand new to ruby, as in, one hour!  So along with perhaps
answering my very basic question, please feel free to point me to other
resources on the web

How do I fix the following so that entering 'q' indeed breaks out of
the loop?  I've read the following but think I will need to see an
example to truly understand.

Thanks in advance

BTW I always learn new language basics by figuring out how to convert
to roman numerals


arabic = ' '
while arabic != 'q' do
  puts "Enter a whole number from 1 to 3999 for conversion"
  puts "to Roman Numerals (enter 'q' to exit)"
  arabic = gets
end

4.scope issue of variable in iterator

5.Newbie Question: Global variable vs. Top-level variable

Hi, group!

This morning, a question came into my mind (I'm still a newbie).
What's the meaning of a top-level variable?

t = "top"
$g = "global"

puts t
puts $g

def f
  puts t #error
  puts $g
end

f

I know that a top-level variable cannot be used in a method.

My questions are:

1. Do you use top-level variables instead of global variables if you
don't need to use it in a method? Is it a good practice to use it like
that?

2. What is a top-level variable? Is it an object variable or a local
variable or what?

3. What is the exact scope of a top-level variable?


Thanks.
Sam

6. newbie scope question

7. Question about variable scope

8. question modules and class variable scope



Return to ruby

 

Who is online

Users browsing this forum: No registered users and 77 guest