Rails beginner
Rails beginner

Reputation: 14504

Rails array help selecting column

I have this array:

[:dk, #<Domain dk: 8, id: 12, se: 5, com: 5>]

I want to select the dk: 8?

So that the input is: 8

My view:

<% @prices.each do |price| %>
<%= price %><br />
<% end %>

The output:

[:dk, #<Domain dk: 8, id: 12, se: 5, com: 5>]
[:com, #<Domain dk: 8, id: 12, se: 5, com: 5>]

My controller:

def domain
  country_codes = %w[ dk com ]

  @domain = "asdsad"

  @results = { }
  @prices = { }

  country_codes.each do |cc|
    @results[cc] = Whois.whois("#{@domain}.#{cc}")
    @prices[cc.to_sym] = Domain.order(cc).first
  end
  render :layout => false
end

Upvotes: 1

Views: 172

Answers (1)

apneadiving
apneadiving

Reputation: 115521

You don't have an Array, you have a Hash.

Do this:

<% @prices.each do |cc,domain| %>
  <%= domain.send(cc) %><br />
<% end %>

So:

  • first: #<Domain dk: 8, id: 12, se: 5, com: 5>.send(:dk) # => 8
  • second: #<Domain dk: 8, id: 12, se: 5, com: 5>.send(:com) # => 5

Upon request, further explanation.

  • you create a Hash: @prices = { }

  • then you fill it: @prices[cc.to_sym] = Domain.order(cc).first

The latest means to you add to the hash one object: Domain.order(cc).first, with it's key: cc.to_sym

Upvotes: 2

Related Questions