简体   繁体   中英

ruby How I could print without leave newline space for each line?

ruby How I could print without leave newline space for each line

this is my file

name1;name2;name3

name4;name5;name6

I have this command

File.open("text2xycff.txt", "r") do  |fix|
  fix.readlines.each do |line|
    parts = line.chomp.split(';') 

input3= zero

 File.open('text2xyczzzz2.txt', 'a+') do |f| 
   f.puts  parts[0] ,  parts[1], parts[2]  ,input3
 end



end

end

this is my output

name1

name2

name3

zero

name4 

name5

name6

zero

I need to output this

name1;name2;name3;zero

name4;name5;name6;zero

Please help me whit this problem

A more minimal approach is to just append something to each line:

File.open("text2xycff.txt", "r") do  |input|
  File.open('text2xyczzzz2.txt', 'a+') do |output| 
    input.readlines.each do |line|
      output.puts(line.chomp + ';zero')
    end
  end
end

Or if you want to actually parse things, which presents an opportunity for clean-up:

File.open("text2xycff.txt", "r") do  |input|
  File.open('text2xyczzzz2.txt', 'a+') do |output| 
    input.readlines.each do |line|
      parts = line.chomp.split(/;/)
      parts << 'zero'

      output.puts(parts.join(';'))
    end
  end
end

If you call puts with comma-separated arguments, each one of them will be printed on a different line.

You can use ruby string interpolation here ( http://ruby-for-beginners.rubymonstas.org/bonus/string_interpolation.html ):

f.puts "#{parts[0]};#{parts[1]};#{parts[3]};#{input3}"

You have two solutions.

The first one uses puts as you currently do:

File.open('yourfile.txt', 'a+') { |f|
    f.puts "#{parts[0]}#{parts[1]}#{parts[2]}#{input3}"
}

The second one uses write instead of puts :

File.open('yourfile.txt', 'a+') { |f| 
    f.write parts[0]
    f.write parts[1]
    f.write parts[2]
    f.write input3
}

Try:

File.open("test_io.txt", "r") do  |fix|
  fix.readlines.each do |line|
    File.open('new_file10.txt', 'a+') do |f|
      next if line == "\n"
      f.puts "#{line.chomp};zero"
    end
  end
end

I'm not sure why you're splitting the string by semicolon when you specified you wanted the below output. You would be better served just appending ";zero" to the end of the string rather than parsing an array.

name1;name2;name3;zero

name4;name5;name6;zero

You can specify an if statement to check for the zero value.

Example:

arr = ["name1", "name2", "name3", "zero", "name4", "name5", "name6", "zero"];
arr.each { |x|
  if x != "zero" then
    print x
  else
    puts x
  end
}

Output:

name1name2name3zero
name4name5name6zero

print will print inline.

puts will print on a new line.

Just implement this logic in your code and you're good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM