tags:

views:

104

answers:

3

I have Ruby code similar to:

ok.rb
hasil = "input operator salah"
 puts hasil

exec("sort ok.rb > output.txt") if fork.nil?

It just wrote all code into output.txt. However, I only want hasil result to be written to output.txt. How should I modify the code for such an end result?

+2  A: 

You've executed the sort command taking ok.rb as the input. Instead, you want to run ok.rb and take its output as the input to sort.

Without knowing Ruby, I'd expect this to be something like:

exec("ruby ok.rb | sort > output.txt") if fork.nil?

I've just tried this from my Linux desktop and it worked fine:

ok.rb:

hasil = "input operator salah"
puts hasil

other.rb:

exec("ruby ok.rb | sort > output.txt") if fork.nil?

Execute:

$ ruby other.rb
$ cat output.txt
input operator salah

(You've only provided a single line of output so there wasn't exactly a lot to sort.)

Jon Skeet
A: 

i was tried edited with

 exec("ruby ok.rb | sort > output.txt") if fork.nil?

but there'snt result on output.txt

does u have any idea? or give me url for this problem

thanks

Kuya
+1  A: 

The cleanest way would be to change the preceding code to not produce output to stdout directly, but instead to only build the string and then sort this from ruby and print it to the file. Like this for example:

hasil = "input operator salah"

File.open("output.txt", "w") do |f|
  f.puts hasil.split("\n").sort.join("\n")
end

If replacing unix sort with ruby sort is not an option (maybe because sort was just an example and in reality you're piping to a different application that can't easily be replaced with ruby), you can write your code to the application directly instead of writing to stdout. You could even write your code to be general enough to write to any IO.

def generate_output(out)
  hasil = "input operator salah"
  out.puts hasil
end

# If you decide to output the text directly to stdout (without sorting)
generate_output(stdout)

# If you instead want to pipe to sort:
IO.popen("sort > output.txt", "w") do |sort|
  generate_output(sort)
end
sepp2k