in the extract of my script code (see the first piece of code below) I use the array @post_csv_order
to specify the order and key => value relationship of elements for the hash @post[post_id]
. I run the assignment line @post[forum_id] = Hash[*@post_csv_order.flatten]
in a loop when I collected all values (like forum_id, post_title etc). Why I want to have this array? I want to have all the key names (=csv headers) and key => value definition at one place only. So when I change the order or I add new detail I want to store, I do not have to make any more changes anywhere else in the code. I want to have that one array approach even if using object instead of hash.
To create the array @post_csv_order
the second item of the array must be defined otherwise I get undefined local variable or method
.
Little bit more about the whole script: it flows like that- I parse a forum page and that gives me an array of posts.I process that and get all details I want per post and store it.I want to use the array @post_csv_order
at this point, to create new hash of these details. I also want to use the array @post_csv_order
to save all data I got into csv and also to read that csv next time when I run the script so I can update any fields (like last post author,last post date,number of views).
require 'pp'
@post = {}
forum_id = 123
post_title = "Test post"
@post_csv_order = [
["ForumID" , forum_id],
["Post title", post_title]
]
@post[forum_id] = Hash[*@post_csv_order.flatten]
pp @post
so I thought I can fix it by defining all variables used in the array and assigning empty string to them forum_id , post_title = ""
but I am not sure if it's the right way how to do this in ruby.
require 'pp'
@post = {}
forum_id , post_title = ""
@post_csv_order = [
["ForumID" , forum_id],
["Post title", post_title]
]
forum_id = 123
post_title = "Test post"
@post[forum_id] = Hash[*@post_csv_order.flatten]
pp @post
PS. Could somebody suggest or edit the title? I don't know how to name it...