Difference between revisions of "Ruby"
From Suhrid.net Wiki
Jump to navigationJump to searchLine 27: | Line 27: | ||
mc.my_method #calls the method | mc.my_method #calls the method | ||
mc.boo #error, not allowed to access variable | mc.boo #error, not allowed to access variable | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | * An instance variable can only be accessed or modified within a method definition. | ||
+ | |||
+ | <syntaxhighlight lang="ruby"> | ||
+ | |||
+ | class MyClass | ||
+ | def boo #getter method | ||
+ | return @boo | ||
+ | end | ||
+ | |||
+ | def boo=(val) #setter method | ||
+ | @boo = val | ||
+ | end | ||
+ | end | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | <syntaxhighlight lang="bash"> | ||
+ | mc = MyClass.new #create a myclass object | ||
+ | boo = 1 #calls the setter method | ||
+ | mc.boo #calls the getter method | ||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 09:58, 3 September 2014
Philosophy
- Focus is on the programmer rather than the machine. i.e. maximize programmer efficiency.
- Principle of least astonishment - behave in such a way that minimized the confusion of experienced Ruby programmers.
- Ruby is an object-oriented scripting language.
- Multi paradigm :
- Scripting : automate tasks within some environment
- Imperative : traditional control structures
- Object oriented : everything is an object
- Functional : Also exists. Computation proceeds via the evaluation of functions that depend only on their input, not program state.
Classes and Inheritance
class MyClass
@boo #instance variable
def my_method
@foo = 2 #instance variable
end
end
mc = MyClass.new #create a myclass object
mc.my_method #calls the method
mc.boo #error, not allowed to access variable
- An instance variable can only be accessed or modified within a method definition.
class MyClass
def boo #getter method
return @boo
end
def boo=(val) #setter method
@boo = val
end
end
mc = MyClass.new #create a myclass object
boo = 1 #calls the setter method
mc.boo #calls the getter method