Qt : Reading the text file and Displaying in LineEdit - ruby

I have an input file and a batch file. When the batch file is executed using the System command,
a corresponding outfile is generated.
Now I want a particular text (position 350 to 357) from that outfile to be displayed on to my lineedit widget
Here is that part of my code:
system("C:/ORG_Class0178.bat")
Now the outfile will be generated
File.open("C:/ORG_Class0178_out.txt", 'r').each do |line|
var = line[350..357]
puts var
# To test whether the file is being read.
#responseLineEdit = Qt::LineEdit.new(self)
#responseLineEdit.setFont Qt::Font.new("Times NEw Roman", 12)
#responseLineEdit.resize 100,20
#responseLineEdit.move 210,395
#responseLineEdit.setText("#{var}")
end
When I do test whether the file is being read using puts statement, I get the exact required output in editor. However, the same text is not being displayed on LineEdit. Suggestions are welcome.
EDIT: A wired observation here. It works fine when I try to read the input file and display it , however it does not work with the output file. The puts statement does give the answer in editor confirming that output file does contain the required text. I am confused over this scenario.

There is nothing wrong with the code fragments shown.
Note that var is a local variable. Are the second and third code fragments in the same context? If they are in the same method, and var is not touched in-between, it will work.
If the fragments belong to different methods of the same class, than an instance variable (#var) will solve the problem.
If all that does not help, use Pry to chase the problem. Follow the link to find the pre-requisites and how to use. Place binding.pry in your code, and your program will stop at that line. Then inspect what your variables are doing.

try 'rb' instead of 'r'
File.open("C:/ORG_Class0178_out.txt", 'rb').each do |line|
var = line[350..357]
puts var

Related

Ruby I/O Existence Issues

I have a decent amount of knowledge about Ruby code, but I do have an issue with my current project. I use Gosu to make 2D games (and once I figure out how, simple 3D games), so I need a resolution.
And this is where my question comes in, why does Ruby keep giving me an error when seeing if the settings file exists? I've been trying to get it working with the file not existing, which keeps giving me the error, "'initialize': No such file or directory # rb_sysopen - ./settings.set (Errno::ENOENT)" which has been annoying me for the last few days. The file gives no issues and actually works as intended when I leave the file created, but I want it to be where if the file gets deleted off of someone's computer, it rebuilds the file and creates a new one using default values.
Here's the area that it keeps crashing at:
settings = []
settings_file_existance = File.file?("settings.set")
if settings_file_existance == true
File.open("settings.set").readlines.each do |line|
settings.push line
end
else
settings_file = File.open("settings.set")
settings_file.write "800"
settings_file.write "\n"
settings_file.write "600"
settings_file.close
end
I have tried looking for fixes on this site, along with many others, but no one so far has been able to help.
You could try this:
settings = []
if File.file?("settings.set")
settings = File.read("settings.set").split("\n")
else
File.open("settings.set", "w") do |file|
file.write "800\n600"
end
end
As a side note, consider that the above code will set settings only if settings.set file exits, otherwise it will remain in an empty array (i.e. []).
If you wish to avoid that, just define settings with the default values, for example:
settings = [800, 600]
Now if settings.set file doesn't exist, then settings will be [800, 600], otherwise it will be overwritten with the values from settings.set.
To avoid writing 800 and 600 twice, you could use settings variable to get the values to be written in the new file, for example:
file.write(settings.join("\n"))
Putting it all together, your code would look like this:
settings = [800, 600]
if File.file?("settings.set")
settings = File.read("settings.set").split("\n")
else
File.open("settings.set", "w") do |file|
file.write(settings.join("\n"))
end
end

What is wrong with this piece of code(trivial)

This is a very trivial function I wrote to read text as a prompt. It doesn't work but doesn't give me errors either. I've tried all modifications I can think if to get it to work, but to no avail.
Code:
def prompt(query="")
print (query) #I also tried 'print"#{query}"
var = gets()
return var
end
name = prompt("Input your name:")
puts"#{name}"
Nothing happens. This has frustrated me, that I couldn't do something so simple, and I've spent hour on it.
There was no problem with the code itself. It was simply that my editor Sublime Text 3 didn't handle accepting user input well.
How to make scripts run from command line:
Create a file ending in ".rb", for example "my_script.rb"
Run ruby my_script.rb
Don't forget ".rb" ;)

How to import a column of a CSV file into a Ruby array?

My goal is to import a one column of a CSV file into a Ruby array. This is for a self-contained Ruby script, not an application. I'll just be running the script in Terminal and getting an output.
I'm having trouble finding the best way to import the file and finding the best way to dynamically insert the name of the file into that line of code. The filename will be different each time, and will be passed in by the user. I'm using $stdin.gets.chomp to ask the user for the filename, and setting it equal to file_name.
Can someone help me with this? Here's what I have for this part of the script:
require 'csv'
zip_array = CSV.read("path/to/file_name.csv")
and I need to be able to insert the proper file path above. Is this correct? And how do I get that path name in there? Maybe I'll need to totally re-structure my script, but any suggestions on how to do this?
There are two questions here, I think. The first is about getting user input from the command line. The usual way to do this is with ARGV. In your program you could do file_name = ARGV[0] so a user could type ruby your_program.rb path/to/file_name.csv on the command line.
The next is about reading CSVs. Using CSV.read will take the whole CSV, not just a single column. If you want to choose one column of many, you are likely better off doing:
zip_array = []
CSV.foreach(file_name) { |row| zip_array << row[whichever_column] }
Okay, first problem:
a) The file name will be different on each run (I'm supposing it will always be a CSV file, right?)
You can solve this problem with creating a folder, say input_data inside your Ruby script. Then do:
Dir.glob('input_data/*.csv')
This will produce an array of ALL files inside that folder that end with CSV. If we assume there will be only 1 file at a time in that folder (with a different name), we can do:
file_name = Dir.glob('input_data/*.csv')[0]
This way you'll dynamically get the file path, no matter what the file is named. If the csv file is inside the same directory as your Ruby script, you can just do:
Dir.glob('*.csv')[0]
Now, for importing only 1 column into a Ruby array (let's suppose it's the first column):
require 'csv'
array = []
CSV.foreach(file_name) do |csv_row|
array << csv_row[0] # [0] for the first column, [1] for the second etc.
end
What if your CSV file has headers? Suppose your column name is 'Total'. You can do:
require 'csv'
array = []
CSV.foreach(file_name, headers: true) do |csv_row|
array << csv_row['Total']
end
Now it doesn't matter if your column is the 1st column, the 3rd etc, as long as it has a header named 'Total', Ruby will find it.
CSV.foreach reads your file line-by-line and is good for big files. CSV.read will read it at once but using it you can make your code more concise:
array = CSV.read(, headers: true).map do |csv_row|
csv_row['Total']
end
Hope this helped.
First, you need to assign the returned value from $stdin.gets.chomp to a variable:
foo = $stdin.gets.chomp
Which will assign the entered input to foo.
You don't need to use $stdin though, as gets will use the standard input channel by default:
foo = gets.chomp
At that point use the variable as your read parameter:
zip_array = CSV.read(foo)
That's all basic coding and covered in any intro book for a language.

Uploading and parsing text document in Rails

In my application, the user must upload a text document, the contents of which are then parsed by the receiving controller action. I've gotten the document to upload successfully, but I'm having trouble reading its contents.
There are several threads on this issue. I've tried more or less everything recommended on these threads, and I'm still unable to resolve the problem.
Here is my code:
file_data = params[:file]
contents = ""
if file_data.respond_to?(:read)
contents = file_data.read
else
if file_data.respond_to?(:path)
File.open(file_data, 'r').each_line do |line|
elts = line.split
#
#
end
end
end
So here are my problems:
file_data doesn't 'respond_to?' either :read or :path. According to some other threads on the topic, if the uploaded file is less than a certain size, it's interpreted as a string and will respond to :read. Otherwise, it should respond to :path. But in my code, it responds to neither.
If I try to take out the if statements and straight away attempt File.open(file_data, 'r'), I get an error saying that the file wasn't found.
Can someone please help me find out what's wrong?
PS, I'm really sorry that this is a redundant question, but I found the other threads unhelpful.
Are you actually storing the file? Because if you are not, of course it can't be found.
First, find out what you're actually getting for file_data by adding debug output of file_data.inspect. It maybe something you don't expect, especially if form isn't set up correctly (i.e. :multipart => true).
Rails should enclose uploaded file in special object providing uniform interface, so that something as simple as this should work:
file_data.read.each_line do |line|
elts = line.split
#
#
end

Pushin each_line into array not working

I've got a weird issue with Ruby. I want to read data from a file and put the data then into an array.
The weird thing is, it's working in another script which does basically, the same thing.
quoteArray = []
quoteFile = File.new("quotes.txt", "r") or die "Unable to open file..."
quoteFile.each_line { |line| quoteArray.push line }
puts quoteArray[0]
All I get out of this is an array with one element where the whole text file is in. What's wrong? Is it my machine? The text file? Any ideas?
Thanks in advance
quoteFile = File.read("quotes.txt").gsub(/\n?\r/, "\n").lines.to_a
You are printing quoteArray[0]. Try printing quoteArray.inspect and see what you get.
It works fine for me. Make sure that your text file has multiple lines in it and not just a one single big line.

Resources