Forum: Ruby on Rails Associative arrays

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Daf46a55e32d22921891cf83c5d872b9?d=identicon&s=25 Spectre013 (Guest)
on 2005-12-16 17:54
(Received via mailing list)
I just started playing with rails this week and am working on porting
our
existing website to rails

in our navigation we have a list that has the days of the week that link
to
the articles for those days.

this seems to be working when I had it in the template it would give me
the
array I was looking for so I decided to move it to the helper so that I
could use it on all my templates.
Application_helper.rb
------------------------------------------------
def days
         t=Time.now()
         #days =
['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
         #YY,MM,DD,h,m,s
        days = Array.new
        for i in 1..8
            d = Time.local(t.year,t.month,t.day-i)
            #n = d.to_i
            today = d.strftime("%A")
            days.insert('today',d.to_i)
        end
    end
-----------------------------------------------------------



I know this is not correct but it is what I am looking to do.
when the above code was in the template minus the def these lines would
spit
out the error about converting strings to integers.

application.rhtml

<li><a href="/index/<%= days['Monday'] %>">Monday</a></li>
<li><a href="/index/<%= days['Tuesday'] %>">Tuesday</a></li>
<li><a href="/index/<%= days['Wednesday'] %>">Wednesday</a></li>
<li><a href="/index/<%= days['Thursday'] %>">Thursday</a></li>
<li><a href="/index/<%= days['Friday'] %>">Friday</a></li>
<li><a href="/index/<%= days['Saturday'] %>">Saturday</a></li>
<li><a href="/index/<%= days['Sunday'] %>">Sunday</a></li>

I am coming from about 7 years of php background so go easy on me :)

Thanks for your help
280b41a88665fd8c699e83a9a25ef949?d=identicon&s=25 Stephen Waits (Guest)
on 2005-12-16 22:33
(Received via mailing list)
Spectre013 wrote:
>
> in our navigation we have a list that has the days of the week that link
> to the articles for those days.

I don't know about your specific case, but since nobody replied, I just
thought I'd chime in that in Ruby land we use 'class Hash' for
Associative Arrays.

HTH..

--Steve
Accad816054fc1b2fa7dae2a2fce5266?d=identicon&s=25 Cuong Tran (Guest)
on 2005-12-16 23:24
(Received via mailing list)
Helpers are just methods so you can't really access them this way.
You can call days() inside your template and assign it to a variable:

<%  days = get_days() %>
A2b2f4ee23989dc68529baef9cbddcd6?d=identicon&s=25 Julian 'Julik' Tarkhanov (Guest)
on 2005-12-17 00:46
(Received via mailing list)
On 16-dec-2005, at 16:51, Spectre013 wrote:

> ------------------------------------------------
>             today = d.strftime("%A")
>
> I am coming from about 7 years of php background so go easy on me :)
>
> Thanks for your help

You need Hash.new (or just {} ) instead of Array.new. Array will
complain if you feed it Strings as keys - moreover, when you set a
key in an Array which does not exist, the interval to the last
existing key will be filled with nils.

For example:

ar = [1,2,3,4,5]
ar[7] = 3

ar # will be [1, 2, 3, 4, 5, nil, nil, 3]

Beware though that Ruby hashes are UN-ordered (which means that you
can't set months there and then iterate through them in the same order)

myhash = {}
hash[:key1] = 2
hash[:key2] = 4 etc.

but when you iterate over them with each_pair you might as well get
key2 first.
Fe9b2d0628c0943af374b2fe5b320a82?d=identicon&s=25 Eero Saynatkari (rue)
on 2005-12-17 02:27
Spectre013 wrote:
> I just started playing with rails this week and am working on porting
> our
> existing website to rails
>
> in our navigation we have a list that has the days of the week that link
> to
> the articles for those days.
>
> this seems to be working when I had it in the template it would give me
> the
> array I was looking for so I decided to move it to the helper so that I
> could use it on all my templates.
>
> <code elided/>

You must use a Hash instead of an Array in this
case (beware, not tested):

  # This should work
  def weekdays()
    @weekdays = {}
    7.times {|i|
      # I believe Rails provides Time#days, or just sub 60*60*24*i
      d = Time.now - i.days
      @weekdays[d.strftime("%A")] = d.to_i
    }
    @weekdays
  end

  # You could be fancy and use Enumerable#inject
  def weekdays2()
    # 'inject' an empty Hash to be filled
    (0...7).to_a.inject({}) {|hash, i|
      d = Time.now - i.days
      hash[d.strftime("%A")] = d.to_i
      hash
    }
  end

Then you can call it as

  weekdays['Monday']

  # Or

  @days = weekdays
  @days['Tuesday']

> I know this is not correct but it is what I am looking to do.
> when the above code was in the template minus the def these lines would
> spit
> out the error about converting strings to integers.

The error is simply due to Arrays only accepting
numeric indices.

>
> Thanks for your help


E
Fe9b2d0628c0943af374b2fe5b320a82?d=identicon&s=25 Eero Saynatkari (rue)
on 2005-12-18 06:31
Eero Saynatkari wrote:
> Spectre013 wrote:
>
> <snip earlier/>

I was modestly intrigued by the question..
here is the more-or-less final version I
came up with since I wanted a one-liner:

  require 'date'
  require 'time'

  def weekdays()
    ((Date.today - 6)..today).inject({}) {|h, d| h[d.strftime("%A")] =
Time.parse(d).to_i; h}
  end                             # weekdays()

  weekdays['Monday']              # etc.


Of course, it might be desirable to use some
other kind of URL rather than Time#to_i, for
example just '2005/12/18', for example. That
should be simple enough to substitute for the
Time.parse call.


E
Afc7838e1e6873fbf99f4877e797c26e?d=identicon&s=25 Ivan Storck (ivanstorck)
on 2005-12-18 10:09
(Received via mailing list)
If I have a collection_select in my form, should it automatically
update the id for the table it is populating with the foreign key?  I
don't think it is, because the code as it is now is leaving person_id
as nil.  Any suggestions?

in _form.rthml

<p><label for="person_id">Paid by</label><br/>
<%= @people = Person.find(:all )
  collection_select(:person, :fullname, @people, :id, :fullname)
%>

models:


class Bill < ActiveRecord::Base
	belongs_to :person
end

class Person < ActiveRecord::Base
	has_many :bills
end


Thanks,
-
Ivan Storck
25e11a00a89683f7e01e425a1a6e305c?d=identicon&s=25 Wilson Bilkovich (Guest)
on 2005-12-18 21:38
(Received via mailing list)
On 12/18/05, Ivan Storck <ivan@sustainablemarketing.com> wrote:
> If I have a collection_select in my form, should it automatically
> update the id for the table it is populating with the foreign key?  I
> don't think it is, because the code as it is now is leaving person_id
> as nil.  Any suggestions?
>
Assuming @bill is the instance variable for the Bill object, try:
<p><label for="bill_person_id">Paid by</label><br/>
<%= select 'bill', 'person_id', Person.find(:all).collect {|p|
[p.fullname, p.id]} %>
This topic is locked and can not be replied to.