Forum: Ruby What is wrong in this

Posted by Mallikarjuna Yaddala (mallikarjunece)
on 2012-12-04 12:45
$rr_msg = "hello"

task :default do
        display "rr"
end

def display(msg)
        ss = msg+"_msg"
        puts "#{$ss}"
end


My aim is to construct a global var ($rr_msg) and get the value ...

Can any one help me ......
Posted by "Jesús Gabriel y Galán" <jgabrielygalan@gmail.com> (Guest)
on 2012-12-04 13:01
(Received via mailing list)
On Tue, Dec 4, 2012 at 12:45 PM, Mallikarjuna Yaddala
<lists@ruby-forum.com> wrote:
>
>
> My aim is to construct a global var ($rr_msg) and get the value ...

You can't construct a variable like that. In order to do this you need
to use eval:

1.9.2p290 :001 > $rr_msg = "test"
 => "test"
1.9.2p290 :002 > var = "rr"
 => "rr"
1.9.2p290 :004 > eval "$#{var}_msg"
 => "test"

But there's another way. Instead of constructing a variable, you could
create a hash whose keys are the "variables":

$messages = {"rr" => "test"} # not sure it needs to be global, but 
whatever

def display message_id
  puts $messages[message_id]
end

display "rr"  #=> test

Jesus.
Posted by Chad Perrin (Guest)
on 2012-12-07 05:29
(Received via mailing list)
On Tue, Dec 04, 2012 at 09:00:56PM +0900, Jes
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.