Mapping a String to Properties - A Better Way?

I have a piece of code that works fine, but I’m wondering if there is
a better way to go about it. The method is receiving a hash (params)
and in that hash are a group of items named item_1, item_2, item_3,
and so on. Each of these items contains a whitespace separated list
of values. For instance:

item_1 => “120 355 240 145”
item_2 => “130 400 100 100”

These values map to x, y, width, and height properties on an object.

Here’s my code, but is there a better, more Ruby way to do this:

params.each do |key, value|
  if key =~ /^item_/
    a = value.split
    Item.update(key.split("_")[1],
                                :x => a[0],
                                :y => a[1],
                                :width => a[2],
                                :height => a[3])
  end
end

Thanks in advance for any pointers.

Michael

maybe like that?

params.each do |key, value|
key = key.split(’’)
if key[0] == 'item

x, y, width, height = value.split
Item.update key, :x => x, :y => y, :width => width, :height =>
height
end
end

On 15/05/06, Michael F. [email protected] wrote:

maybe like that?

params.each do |key, value|
key = key.split(’_’)

Doesn’t this update the hash key back up in the caller?

I forgot about parallel assignments. I like that. I’d probably keep
the regex or at least not alter the key as Dick stated. I’d be
interested to know if it does make a difference. Thanks.

Michael

Well that’s good to know. Thanks.

Michael

No, it keeps the hash intact - just try it in irb :slight_smile:

(h = {1,2,3,4}).each{|key, value| key += 2}
=> {1=>2, 3=>4}

Michael F. wrote:

params.each do |key, value|
key = key.split(’’)
if key[0] == 'item

Minor improvement (IMHO):

key = key[/^item_(\d+)$/, 1]
if key then

end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs