How should I store list of single values? - ruby

I am currently writing a Ruby script to manage my dotfiles. I want to keep a list of the tracked dotfiles, and am not quite sure how to go about this.
The thing is that the list would be so simple, e.g
tmux.conf
zshrc
vimrc
so I feel using yml, xml or various other formats would be overkill. I do not need to store indexes, paths, order or anything of the sort. However, storing the filesnames in a file separated by newlines or commas still feel kind of "dumb". How should I go about this?
UPDATE
It seems like my question wasn't clear enough. I know how to write to and read from files and DB using Ruby. My question was meant to be something like What is the best practice for storing single-values in a file?
Should I use a known file format like YAML or XML, or what would you choose?

through this you can get all file name in an array now you can write them to file
file_names = Dir.entries(".").select {|f| !File.directory? f}
file = File.open(local_filename, 'w')
file_names.each do |name|
file.write(name + "\n")
end

I'd simply go with new-line separated values or storing it inside the script. It's definitely not dumb, it's just the way you do things like that.

Related

I want to make a english word-meaning dictionary as a file/folder, what will be the most efficient way to access it?

So i want to make a dictionary and there are two ways i can think of accomplishing this
a dictinary directory where each word is stored as a filename with its meaning as the filecontent
a single file with all words
First question can someone suggest any better way to store a dictionary which is efficient ? (i have to store this as a file)
Second question which of 2 methods suggested by me is more faster to access ?
Please note i am not going to search through this directory since it will be huge rather only check if the word exists or not by checking if the file exists and then print its content if its exists.
Edit: added how am i going to use the dictionary as suggested by #Vlad Feinstein
The most important part is missing from your question: how are you going to use that dictionary?
However, in order to access words stored in individual files you would have to use OS-provided API, that is most likely less efficient that to go through data in a single file.
Please note that many words have multiple meanings. Did you consider some popular data formats, like JSON, to store all that?

How to split a large csv file into multiple files in GO lang?

I am a novice Go lang programmer,trying to learn Go lang features.I wanted to split a large csv file into multiple files in GO lang, each file containing the header.How do i do this? I have searched everywhere but couldnt get the right solution.Any help in this regard will be greatly appreciated.
Also please suggest me a good book for reference.
Thanking You
Depending on your shell fu this problem might be better suited for common shell utilities but you specifically mentioned go.
Let's think through the problem.
How big is this csv file? Are we talking 100 lines or is it 5G ?
If it's smallish I typically use this:
http://golang.org/pkg/io/ioutil/#ReadFile
However, this package also exists:
http://golang.org/pkg/encoding/csv/
Regardless - let's return to the abstraction of the problem. You have a header (which is the first line) and then the rest of the document.
So what we probably want to do (if ignoring csv for the moment) is to read in our file.
Then we want to split the file body by all the newlines in it.
You can use this to do so:
http://golang.org/pkg/strings/#Split
You didn't mention but do you know how many files you want to split by or would you rather split by the line count or byte count? What's the actual limitation here?
Generally it's not going to be file count but if we pretend it is we simply want to divide our line count by our expected file count to give lines/file.
Now we can take slices of the appropriate size and write the file back out via:
http://golang.org/pkg/io/ioutil/#WriteFile
A trick I use sometime to help think me threw these things is to write down our mission statement.
"I want to split a large csv file into multiple files in go"
Then I start breaking that up into pieces but take the divide/conquer approach - don't try to solve the entire problem in one go - just break it up to where you can think about it.
Also - make gratiutious use of pseudo-code until you can comfortably write the real code itself. Sometimes it helps to just write a short comment inline with how you think the code should flow and then get it down to the smallest portion that you can code and work from there.
By the way - many of the golang.org packages have example links where you can literally run in your browser the example code and cut/paste that to your own local environment.
Also, I know I'll catch some haters with this - but as for books - imo - you are going to learn a lot faster just by trying to get things working rather than reading. Action trumps passivity always. Don't be afraid to fail.
Here is a package that might help. You can set a necessary chunk size in bytes and a file will be split on an appropriate amount of chunks.

systematically changing filenames in a directory w/ Ruby

I'd like to grab all the files in a particular directory, and then apply a gsub(/abc/,'z') to all the filenames and essentially resave the files under the new filenames, how do I do that?
I've been looking at File but I don't seem to have any of the parameters that it requires, aka the filename, etc.
M
File.rename(from, to) along with Dir.entries (or Dir.foreach)?
Dave's answer is right on. Here's an example:
Dir.glob("*.rb").each do |fname|
File.rename(fname, fname.gsub(/\.rb/,".rbb"))
end
Dir.glob allows you to select files based on some given criteria, but like Dave says, you could also use Dir.entriesor Dir.foreach

Parsing text files and sorting in Ruby?

I would like to write a Ruby program which can parse three separate text files, each containing different delimiters, then sort them according to certain criteria.
Can someone please point me in the right direction?
It is not clear what is the data format in your files, and what criteria you used to sort, so I am not able to provide you a accurate answer.
However, basically, you might need something like this:
File.open("file_name","r").read.split(",").sort_by {|x| x.length}
You:
Opened a file using File.open.
Read the whole file and got a string. You can also read the file line-by-line using the each method.
Split the string use split. The delimiter used is ,.
Use sort_by to sort them according to the criteria specified in the block.
Enumerable#sort_by will allow you to sort an array (or other enumerable object) with a specific comparison function.
If by "text files with delimiters" you mean CSV files (character seperated values), then you can use the csv library, which is part of the standard library, to parse them. CSV gives you objects that look and feel like Ruby Hashes and Arrays, so you can use all the standard Ruby methods for sorting, filtering and iterating, including the aforementioned Enumerable#sort_by.

Java .properties file equivalent for Ruby?

I need to store some simple properties in a file and access them from Ruby.
I absolutely love the .properties file format that is the standard for such things in Java (using the java.util.Properties class)... it is simple, easy to use and easy to read.
So, is there a Ruby class somewhere that will let me load up some key value pairs from a file like that without a lot of effort?
I don't want to use XML, so please don't suggest REXML (my purpose does not warrant the "angle bracket tax").
I have considered rolling my own solution... it would probably be about 5-10 lines of code tops, but I would still rather use an existing library (if it is essentially a hash built from a file)... as that would bring it down to 1 line....
UPDATE: It's actually a straight Ruby app, not rails, but I think YAML will do nicely (it was in the back of my mind, but I had forgotten about it... have seen but never used as of yet), thanks everyone!
Is this for a Rails application or a Ruby one?
Really with either you may be able to stick your properties in a yaml file and then YAML::Load(File.open("file")) it.
NOTE from Mike Stone: It would actually be better to do:
File.open("file") { |yf| YAML::load(yf) }
or
YAML.load_file("file")
as the ruby docs suggest, otherwise the file won't be closed till garbage collection, but good suggestion regardless :-)
Another option is to simply use another Ruby file as your configuration file.
Example, create a file called 'options'
{
:blah => 'blee',
:foo => 'bar',
:items => ['item1', 'item2'],
:stuff => true
}
And then in your Ruby code do something like:
ops = eval(File.open('options') {|f| f.read })
puts ops[:foo]
YAML will do it perfectly as described above. For an example, in one of my Ruby scripts I have a YAML file like:
migration:
customer: Example Customer
test: false
sources:
- name: Use the Source
engine: Foo
- name: Sourcey
engine: Bar
which I then use within Ruby as:
config = YAML.load_file(File.join(File.dirname(__FILE__), ARGV[0]))
puts config['migration']['customer']
config['sources'].each do |source|
puts source['name']
end
inifile - http://rubydoc.info/gems/inifile/2.0.2/frames will support basic .properties files and also .ini files with [SECTIONS] eg.
[SECTION]
key=value
YAML is good when your data has complex structure but can be fiddly with spaces, tabs, end of lines etc - which might cause problems if the files are not maintained by programmers. By contrast .properties and .ini files are more forgiving and may be suitable if you don't need the deep structure available through YAML.
Devender Gollapally wrote a class to do precisely that:
...though i'd recommend better to use a YAML file.
Instead of the .properties style of config file, you might consider using YAML. YAML used in Ruby on Rails for database configuration, and has gained in popularity in other languages (Python, Java, Perl, and others).
An overview of the Ruby YAML module is here: http://www.ruby-doc.org/core/classes/YAML.html
And the home page of YAML is here: http://yaml.org

Resources