user1667218
user1667218

Reputation: 49

Push into Ruby array variables while declaring them

Basically I want to add into array or hash variables/values at the same time when I'm passing them values.
TL;DR - I don't want to copy-paste variable names and write N lines of code with

array_name << var
array_name << another_var
...
array_name << last_var

--
I wrote this.

def describe_card(card_url)
=begin
Parse card.php?id=<ID> into array.
=end
  @card_array = Array.new
  # http://blog.noort.be/2011/02/12/nokogiri-scraping-with-cookies.html
  @card_page = open(card_url, 'Cookie' => 'city=3')
  @card_doc = Nokogiri::HTML(@card_page)

  @company_id = URI(card_url).query.split('id=')[1]
  @company_name = @card_doc.css('.company_name')
  @company_site = @card_doc.css('.company_site')['href']
  @company_character = @card_doc.css('.company_character')
  @company_description = @card_doc.css('.company_description p')
  @company_ads_quantity = @card_doc.css('.ads_name').length
  @company_office_name = @card_doc.css('#filial_name_view')
  @company_office_address = @card_doc.css('#filial_address_view')
  @company_ymap_link = @card_doc.css('.ymaps-logo-link ymaps-logo-link-ru')

  @card_array
end

@card_array is empty. I need to fill it. I can write 9 lines with << or #push methods but something tells me that it's not so brilliant.

This array will be joined maybe with ad_array and will be inserted into all_ad_array. For the first time writing the result into CSV will be enough for me. Maybe I'm not sure what to use - arrays or hashes. (And it's about 6000 lines/rows in the final array/hash. You can also advice me should I use sqlite or some new NoSQL database.)

I remember there was a nice example probably using #map method. Anyway I really hope that somebody of you will advice me how to write a little bit better and elegant code in this situation. Thanks.

I'm asking there because if I will begin to read Ruby Book again it will be 2-3 days or about a week. But I want to write this code because practice is the best teacher.

Upvotes: 1

Views: 1049

Answers (2)

ck3g
ck3g

Reputation: 5929

You be able to use push with splat operator

array_name.push *array_of_vars

For example:

> [1, 2, 3].push *[4, 5]
=> [1, 2, 3, 4, 5]

Upvotes: 1

Mori
Mori

Reputation: 27789

You could add values to the array at the same time that you assign them to instance variables, e.g.:

@card_array << @company_name = @card_doc.css('.company_name')

Upvotes: 2

Related Questions