[ ruby ] def whatever_function=(param) : defines a setter ( Virtual Attributes / Uniform Access Principle )

Practical Example

You might want to access the duration in minutes and fractions of a minute, rather than in seconds as we’ve been doing.

class Song
def durationInMinutes
@duration/60.0 # force floating point
end
def durationInMinutes=(value)
@duration = (value*60).to_i
end
end
aSong = Song.new("Bicylops", "Fleck", 260)
aSong.durationInMinutes » 4.333333333
aSong.durationInMinutes = 4.2
aSong.duration » 252

Other Example 

class Foo
def foo=(x)
puts "OK: x=#{x}"
end
end
f = Foo.new
f.foo = 123 # => 123
# OK: x=123

Note also that such setter methods always return their argument.

top-level setter method

def bar=(y)
puts "OK: y=#{y}"
end
bar = 123 # => 123, sets the variable "bar".
bar # => 123
Object.new.bar = 123 # => 123, calls our method
# OK: y=123
Object.public_methods.grep /bar/ # => ["bar="]

Other ruby

has_full_name? : is expected to return a boolean value if the object has a full_name

revert_full_name! :

ref : http://ruby-doc.com/docs/ProgrammingRuby/html/tut_classes.html#UC,

https://stackoverflow.com/questions/25960406/what-does-def-function-param-mean-in-ruby,

https://stackoverflow.com/questions/5398919/what-does-the-equal-symbol-do-when-put-after-the-method-name-in-a-method-d,

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s