raj_acharya
raj_acharya

Reputation: 665

file read in ruby getting output as spaces in character

I have an function to read data from file but I have problem with reading data

input in file: 1,S1­-88,S2­-53,S3­-69,S4­-64

File.open(file_path).each do |line|
    p line.gsub(/\s+/, "")
end

Output: "1,S1 ­-88,S2 ­-53,S3 ­-69,S4­ -64 \n"

The problem is, it adding an extra space after s1 -integer,s2 -integer like so, I have tried .gsub(/\s+/, "") to remove white space from string but it is not working, Please can any one help me why this happenning, How I can override this issue Or it may be file encoding issue?

Upvotes: 0

Views: 614

Answers (1)

arjun
arjun

Reputation: 1614

If you binread, essentially you have UTF-8 characters in between

irb(main):013:0> f = File.binread('f2.txt')
=> "1,S1\xC2\xAD-88,S2\xC2\xAD-53,S3\xC2\xAD-69,S4\xC2\xAD-64"

\xC2\xAD are essentially whitespace characters

This may be because you have copied it from somewhere incorrectly or it was introduced in your text because of God. Don't know. You an check here, it shows there are hidden characters in between your text.

This will remove all characters not wanted.

File.foreach('f2.txt') do |f|
 puts f.gsub(/[^\\s!-~]/, '')
end

=> 1,S1-88,S2-53,S3-69,S4-64

Upvotes: 4

Related Questions