-1

So I have a following method which works, without the use of stdin or stdout.

def main(lines)
  lines.each_index do |i|
    word = lines[i]
    if word.length > 1 && word.length <=11 
    puts "I use #{word}"
  end
  end
end

main(["Google", "yahoo", "stackoverflow", "reddit"])

But I am trying to understand how stdin and stdout works with the above.

So when the stdin is “Google”, stdout is “I use Google”

I had to replace main(readlines) with the above array just to make it work.

main(readlines) ===> main(["Google", "yahoo", "stackoverflow", "reddit"])

I don’t know how to implement a command line that does this.

For stdouts would it come before puts?

stdout.puts "I use #{word}"
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • They are defined as both, global variables and constants. You can use `$stdout.puts` or `STDOUT.puts`. Same for `$stderr` / `STDERR`. See the docs for [pre-defined global variables](https://ruby-doc.org/core-2.7.0/doc/globals_rdoc.html). The `puts` method you invoke is [`Kernel#puts`](https://ruby-doc.org/core-2.7.0/Kernel.html#method-i-puts) – the docs mention that it's equivalent to `$stdout.puts(...)` – Stefan Feb 27 '20 at 17:27
  • Consider writing, `lines.each do |line|; puts "I use #{line}" if (1..11).cover?(line.length); end`. – Cary Swoveland Feb 27 '20 at 22:38
  • Ruby defaults to using STDIN/STDOUT for reading and writing to the normal console, so don't explicitly use a channel designator unless it's to a non-standard channel, like a file. Adding them without a good reason just adds visual noise and potential confusion to anyone else maintaining the code. "Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability." — John Woods – the Tin Man Feb 28 '20 at 00:48
  • Currently it's not clear why you'd want to do this. See "[ask]". A use-case might clear that up. – the Tin Man Feb 28 '20 at 00:51

1 Answers1

1

Use one of these ways:

$stdout.puts "I use #{word}"

or

STDOUT.puts "I use #{word}"

For more information see "Difference between $stdout and STDOUT in Ruby".

You can make your script simpler:

def main(lines)
  lines.each_with_index do |i,v| # or use each instead if u just want only the value and change |i,word| to |word|
    if word.length > 1 && word.length <=11 
    puts "I use #{word}"
  end
  end
end
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Darun Omar
  • 21
  • 5