Search the web
Sign In
New User? Sign Up
rails_artist · Only Ruby on Rails Artist here
? Already a member? Sign in to Yahoo!

Yahoo! Groups Tips

Did you know...
Message search is now enhanced, find messages faster. Take it for a spin.

Best of Y! Groups

   Check them out and nominate your group.
Having problems with message search? Fill out this form to ensure your group is one of the first to be migrated to the new message search system.

Messages

  Messages Help
Advanced
Immutable class or object in ruby   Message List  
Reply | Forward Message #18 of 23 |
hi,
sometimes we want our object or instance variables should be immutable (none
changeable).
for example, if you have the following code -
data = ["a", "b"]
call_some_method(data)

you expect "call_some_method" shouldn't change your argument. there are two
way you can ensure immutability.
1. clone your array while you passing through the method.
call_some_method(data.clone)
2. freeze your array so none can change your array.
data.freeze
call_some_method(data)
in this case, if someone try to change the value of data it will throw an
exception.

similarly we can ensure mutability for classes as well, as you know ruby as
great advantage of being open. anytime anywhere you can replace or change
the class behavior.
for example:

class String
def print
puts self
end
end

so sometimes your exposed api should be more preventive, in that case don't
forget to use freeze.
for example - if String class was freezed you won't be able to modify this
class anymore.

hope this will help to understand where should you use freeze.

best wishes,
--
----------------------------------------------------
nhm tanveer hossain khan (hasan)
http://hasan.we4tech.com
----------------------------------------------------
mobile: +880 1713 090 511
----------------------------------------------------
"work for fun"


[Non-text portions of this message have been removed]




Mon Dec 24, 2007 5:08 pm

hasan83bd
Offline Offline
Send Email Send Email

Forward
Message #18 of 23 |
Expand Messages Author Sort by Date

hi, sometimes we want our object or instance variables should be immutable (none changeable). for example, if you have the following code - data = ["a", "b"] ...
nhm tanveer hossain k...
hasan83bd
Offline Send Email
Dec 24, 2007
5:08 pm
Advanced

Copyright © 2009 Yahoo! Inc. All rights reserved.
Privacy Policy - Terms of Service - Guidelines - Help