Download 11084863 Emerson Ong Iteration #!/usr/bin/ruby ary = [1,2,3,4,5] ary

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
11084863
Emerson Ong
Iteration
#!/usr/bin/ruby
ary = [1,2,3,4,5]
ary.each do |i|
puts i
end
Source: http://www.tutorialspoint.com/ruby/ruby_iterators.htm
Everything has a value
1. # p019mtdarry.rb
2. # if you give return multiple parameters,
3. # the method returns them in an array
4. # The times method of the Integer class iterates block num times,
5. # passing in values from zero to num-1
6.
7. def mtdarry
8.
10.times do |num|
9.
square = num * num
10.
return num, square if num > 5
11. end
12. end
13.
14. # using parallel assignment to collect the return value
15. num, square = mtdarry
16. puts num
17. puts square
Source: http://perl.about.com/od/rubytutorials/a/rubyeachloop_2.htm
Symbols are not lightweight Strings
# typical use cases
# access hash value
user = User.find(params[:id])
# name something
attr_accessor :first_name
# set hash value in opts parameter
db.collection.update(query, update, multi: true, upsert: true)
Source: http://stackoverflow.com/questions/11447537/using-ruby-symbols
Everything is an Object
>> class AnotherClass
>>
2 + 3
>> end
=> 5
Source: http://rubylearning.com/blog/2010/09/27/almost-everything-is-an-object-and-everything-isalmost-an-object/
Variable Constants
#!/usr/bin/ruby
$global_variable = 10
class Class1
def print_global
puts "Global variable in Class1 is #$global_variable"
end
end
class Class2
def print_global
puts "Global variable in Class2 is #$global_variable"
end
end
class1obj = Class1.new
class1obj.print_global
class2obj = Class2.new
class2obj.print_global
Source: http://www.tutorialspoint.com/ruby/ruby_variables.htm
Naming conventions
1.
2.
3.
4.
5.
6.
7.
8.
#
#
x
x
x
p007dt.rb
Ruby is dynamic
= 7
# integer
= "house" # string
= 7.5
# real
# In Ruby, everything you manipulate is an object
'I love Ruby'.length
Source: http://rubylearning.com/satishtalim/ruby_names.html
Keyword arguments
# Ruby 1.9:
# (From action_view/helpers/text_helper.rb)
def cycle(first_value, *values)
options = values.extract_options!
name = options.fetch(:name, 'default')
# ...
end
# Ruby 2.0:
def cycle(first_value, *values, name: 'default')
# ...
end
# CAUTION: Not exactly identical, as keywords are enforced:
cycle('odd', 'even', nme: 'foo')
# => ArgumentError: unknown keyword: nme
# To get exact same result:
def cycle(first_value, *values, name: 'default', **ignore_extra)
# ...
end
Source: http://blog.marc-andre.ca/2013/02/23/ruby-2-by-example/
The universal truth
arr = [1, 2, 3]
# bad
for elem in arr do
puts elem
end
# good
arr.each { |elem| puts elem }
Source: http://learncodethehardway.org/blog/AUG_19_2012.html
Access modifiers apply until the end of scope
#!/usr/bin/ruby -w
# define a class
class Box
# constructor method
def initialize(w,h)
@width, @height = w, h
end
# instance method by default it is public
def getArea
getWidth() * getHeight
end
# define private accessor methods
def getWidth
@width
end
def getHeight
@height
end
# make them private
private :getWidth, :getHeight
# instance method to print area
def printArea
@area = getWidth() * getHeight
puts "Big box area is : #@area"
end
# make it protected
protected :printArea
end
# create an object
box = Box.new(10, 20)
# call instance methods
a = box.getArea()
puts "Area of the box is : #{a}"
# try to call protected or methods
box.printArea()
Source: http://www.tutorialspoint.com/ruby/ruby_object_oriented.htm
Method access
1. # p047classaccess.rb
2. class ClassAccess
3.
def m1
# this method is public
4.
end
5.
protected
6.
def m2
# this method is protected
7.
end
8.
private
9.
def m3
# this method is private
10.
end
11. end
12. ca = ClassAccess.new
13. ca.m1
14. #ca.m2
15. #ca.m3
Source: http://rubylearning.com/satishtalim/ruby_access_control.html
Classes are open
1.
2.
3.
4.
5.
6.
7.
class String
def write_size
self.size
end
end
size_writer = "Tell me my size!"
puts size_writer.write_size
Source: http://rubylearning.com/satishtalim/ruby_open_classes.html
Funny method names
name = "sample_string"
name.reverse
name.reverse!
name.is_binary_data?
Source: http://stackoverflow.com/questions/7179016/what-is-the-purpose-of-and-at-the-end-ofmethod-names
Singleton methods
class Foo
def shout
puts "I'm Foo"
end
end
foo=Foo.new
foo.shout
class Foo
def shout
puts "I'm still Foo, but I have been overridden"
end
end
foo.shout
Source: http://rubymonk.com/learning/books/4-ruby-primer-ascent/chapters/39-ruby-s-objectmodel/lessons/131-singleton-methods-and-metaclasses
Missing methods
class MethodCall
def initialize(sym, args)
@sym = sym
@args = args
end
def sym
@sym
end
def args
@args
end
def ==(other_call)
@sym == other_call.sym && @args == other_call.args
end
end
class Spy
def initialize
@method_calls = []
end
# Write your method_missing here
def method_called?(sym, *args)
# Your superiors will call this method to ask you if you've seen
# a particular method call. Simply answer them by returning true
# or false.
end
end
Source: https://rubymonk.com/learning/books/2-metaprogramming-ruby/chapters/25-dynamicmethods/lessons/66-method-missing
Message passing, not function calls
mbmakr = proc do |&blk|
proc {|*args| blk.call(*args)[0..139]}
end
tweetr = mbmakr.call {|msg| msg}
reply = mbmakr.call {|user, msg| "@"+user+": "+msg}
retweetr = mbmakr.call {|user, msg| 'RT '+reply.call(user, msg)}
dmesgr= mbmakr.call {|user, msg| 'D '+user+' '+msg}
retweetr.call "john_x", "French tomato soup is tasty! #protip"
=> "RT @john_x: French tomato soup is tasty! #protip"
Source: http://rubylearning.com/blog/2010/11/03/do-you-understand-rubys-objects-messages-andblocks/
Blocks are Objects; they just don’t know it yet
1. =begin
2.
Ruby Code blocks are chunks of code between braces or
3.
between do- end that you can associate with method invocations
4. =end
5. def call_block
6.
puts 'Start of method'
7.
# you can call the block using the yield keyword
8.
yield
9.
yield
10. puts 'End of method'
11. end
12. # Code blocks may appear only in the source adjacent to a method call
13. call_block {puts 'In the block'}
Source: http://rubylearning.com/satishtalim/ruby_blocks.html
Operators are syntactic sugar
words = ["foo", "bar", "baz"]
words[1]
Source: http://rubymonk.com/learning/books/1-ruby-primer/chapters/6-objects/lessons/37-syntacticsugar-for-special-methods