Is Array constants in the model can be changed during runtime?

Hello everyone!

I have strange problem. Here is the code:

model:

class ItServiceJob < ActiveRecord::Base
TYPES = [["Important", 0], ["Not important", 1], ["SERGEY", 2]]

belongs_to :user
end

view (haml):

  %div{:role => "main", :class => "ui-content"}
    - job_types = ItServiceJob::TYPES
    - job_types.pop if (!can?(:manage, :it_service) || !can?(:born, :sergey))
    = job_types
    = form_for ItServiceJob.new, url: "#" do |f|
      
      %p
        = f.label :type
        = f.select :type, job_types

Now, when I refresh the page every time, the array pops one by one item and finally get empty! But, why? Why the constant changes, not variable? What I’m doing wrong?

Hi,

Constants in Ruby are “contantish”. And in your case you’re passing the array reference to job types, so any changes that you do in job_types it goes to ItServiceJob::TYPES.

With that being said what you need to do is duplicate the ItServiceJob::TYPES. Change the job_type assignment with:

job_types = ItServiceJob::TYPES.dup

Regards,

What is constant is that ItServiceJob::TYPES always gives you the same object (in terms of it object_id), but there is nothing to stop you modifying the object.

Furthermore, job_types = ITServiceJob::TYPES isn’t copying ItServiceJob::TYPES, it is just creating a local variable that references the exact same ruby object. You can copy the array with .dup (this is a shallow copy). If you want to prevent modifications to an object you need to freeze it (by calling .freeze on it). After this any attempts to modify the object will raise an exception

Fred

Sorry for off topic reply, but how do you quote code using gmail? or I should use web interface for posting in group.

Sorry for off topic reply, but how do you quote code using gmail? or I
should use web interface for posting in group.

Click on the three dots on the bottom left of the input text window to
expand the text.

Colin

Oops, I meant code snippets. How to insert them in gmail?

Oops, I meant code snippets. How to insert them in gmail?

Copy/Paste. Best to keep it plain text. IMO at least.

Colin

Thank you for the answers! Will try at work tomorrow!

P.S. I just copy-paste formatted text from another forum =)