Forum: Ruby Open file that its name given by STDIN.gets

Posted by aref aslani (arefaslani)
on 2013-02-02 23:00
Hi all. I'm following the Zed Shaw's ruby tutorials.
in ex15 i've changed this line

filename = ARGV.first

to

filename = STDIN.gets

and this is the command line error:

→ ruby test.rb
test.rb
> test.rb:9:in `initialize': No such file or directory - aref (Errno::ENOENT)
  from test.rb:9:in `open'
  from test.rb:9:in `<main>'

what is the problem?
P.S. the ruby file is attached.
Posted by Colby Callahan (Guest)
on 2013-02-02 23:11
(Received via mailing list)
STDIN.read     ?

The read method reads data from the standard input, until it reaches the
end of the file. The EOF is produced by pressing Ctrl + D on Unix or 
Ctrl +
Z on Windows.
Posted by Stefano Crocco (crocco)
on 2013-02-02 23:15
(Received via mailing list)
On Sunday 03 February 2013 aref aslani wrote
>
> P.S. the ruby file is attached.
>
> Attachments:
> http://www.ruby-forum.com/attachment/8102/Screen_S...
> AM.png
>
>
> --
> Posted via http://www.ruby-forum.com/.

gets returns a string with a trailing newline. This means that, if you 
enter

test

as your file name, the variable filename will contain the string 
"test\n". You
can use String#chomp to remove it:

filename = STDIN.gets.chomp

I hope this helps

Stefano
Posted by aref aslani (arefaslani)
on 2013-02-02 23:19
> filename = STDIN.gets.chomp

ِYou are right:)
that was the problem...
Thank you a lot Stefano :)
Posted by unknown (Guest)
on 2013-02-02 23:21
(Received via mailing list)
Am 02.02.2013 23:00, schrieb aref aslani:
> Hi all. I'm following the Zed Shaw's ruby tutorials.
> in ex15 i've changed this line
>
> filename = ARGV.first
>
> to
>
> filename = STDIN.gets

Please include short code snippets directly in the E-Mail
instead of using attachments!

The string returned from gets is always terminated by a newline
character that you need to remove:

filename = gets.chomp
Posted by aref aslani (arefaslani)
on 2013-02-02 23:24
> Please include short code snippets directly in the E-Mail
> instead of using attachments!
>
> The string returned from gets is always terminated by a newline
> character that you need to remove:

Thank you:) My problem has been solved!
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.