Why set hash with 'eval' doesn't work?

See

Eval creates the variable in his own scope. If you want is to be
available you should use an instance variable

@lic_servers = {...}

and in test.rb

puts @lic_servers

Lars

···

--
Posted via http://www.ruby-forum.com/.

Dear Alex,

Thank you so much for your guide and help, I understand now.

···

--
Posted via http://www.ruby-forum.com/.

Another way is to define the local var before the eval so that it will
be accessible after it.

···

=========================
2. cat test.rb

#!/usr/bin/env ruby

lic_servers = Hash.new # <-- Define it before
csh_file = 'list'
sign = `cat #{csh_file}`
a = eval(sign)
puts a

puts lic_servers

=====

Another example.

10.times do |x|
  my_local = x
end

if defined? my_local
  puts "my_local = #{my_local}"
else
  puts "my_local is not defined"
end

# Second round with local var being defined outside the block
my_local = 0

10.times do |x|
  my_local = x
end

if defined? my_local
  puts "my_local = #{my_local}"
else
  puts "my_local is not defined"
end

# This outputs
my_local is not defined
my_local = 9

Abinoam Jr.

On Thu, Jan 9, 2014 at 6:41 AM, Lars Vonk <lists@ruby-forum.com> wrote:

See
ruby - Variable assignment using eval - Stack Overflow

Eval creates the variable in his own scope. If you want is to be
available you should use an instance variable

@lic_servers = {...}

and in test.rb

puts @lic_servers

Lars

--
Posted via http://www.ruby-forum.com/\.

Lars Vonk wrote in post #1132612:

See
ruby - Variable assignment using eval - Stack Overflow

Eval creates the variable in his own scope. If you want is to be
available you should use an instance variable

@lic_servers = {...}

and in test.rb

puts @lic_servers

Lars

Eval creates the variable in his own scope

Understand now, many thanks.

If you want is to be
available you should use an instance variable

@lic_servers = {...}

May I ask one more question? As I know, instance variable should belongs
to specific class, so here @lic_servers belongs to which class, Main
class?

···

--
Posted via http://www.ruby-forum.com/\.

This is a great question. Actually, an instance variable belongs to an
*instance*, not a class. You can tell which instance by looking at the
self variable. At the top level self points to a magic object called
main (not Main) so that's where @lic_servers lives.

Type "self" and "self.class" at irb to see for yourself.

If it's still unclear, maybe my slides at
http://codelikethis.com/lessons/ruby_objects/objects#state will
clarify.

···

On Thu, Jan 9, 2014 at 5:37 PM, Previn Lin <lists@ruby-forum.com> wrote:

May I ask one more question? As I know, instance variable should belongs
to specific class, so here @lic_servers belongs to which class, Main
class?

--
Alex Chaffee - alex@stinky.com
http://alexchaffee.com
http://codelikethis.com
http://twitter.com/alexch