tags:

views:

63

answers:

3
filename = "#{k}""/kabab" 
extension = ".txt" 

for i in 1..10 
  $stdout=File.open("#{filename}#{co}#{extension}" ,'w')
  puts "sachin"
end

puts "amit"

whats my problem is in last file means kabab10.txt i geeting the output like sachin and amit but i don't want amit to be come in 10th file how to solve it`

A: 

Try using puts to put sachin to the files.

$f = File.open("#{filename}#{co}#{extension}" ,'w')
$f.puts "sachin"
Borealid
i tried amit is still appended there
Amit singh tomar
@amit tomar: If you never reassign stdout, and you call "puts amit", "amit" will be printed to the console. Not to a file. Just run the program with "ruby foo.rb". No pipes or anything.
Borealid
Why use a global variable at all?
Lars Haugseth
A: 

i edit your question but i don't think how you get amit in all your files as you using it out of the loop.But i hope following helps you if you put puts "amit" in for loop

puts "amit" if i != 10

Edited :- Do you like something like following

filename = "kabab" 
extension = ".txt" 

puts "amit"

for i in 1..10 
  $stdout=File.open("#{filename}#{i}#{extension}" ,'w')
    puts "sachin"

end
Salil
no salil i m getting amit in last file means in 10th file o dont want this
Amit singh tomar
+1  A: 

Don't change $stdout, and certainly not without storing away the old value somewhere so you can restore it after you're done with it.

Instead, call puts on the file object:

File.open("#{filename}#{co}#{extension}" ,'w') do |file|
  10.times do
    file.puts "sachin" # This goes to the file
  end
end

puts "amit" # This goes to standard output
Lars Haugseth
thanks lars ...but larsFile.open("#{filename}#{co}#{extension}" ,'w') do |file| 10.times do run end end run body in some other filedef runputs "sachin"now how to do that when i called run as file.run then i have a error like private methos run called for file like that puts "amit
Amit singh tomar
@amit: Send `file` as an argument to your `run` method, and in the run method do `file.puts "amit"`
Lars Haugseth
yaa i did same i would like to know the reason for this error
Amit singh tomar
i also sent file as an argument but just i want to know what is private method run called for file
Amit singh tomar
The File class has an instance method called `run` that is private, meaning it can not be called with an explicit receiver. See for example: http://blog.zerosum.org/2007/11/22/ruby-method-visibility
Lars Haugseth
lars what is this explicit receiver
Amit singh tomar
Follow the link I included in my previous comment, and read it.
Lars Haugseth