130 likes | 252 Vues
Methods. A simple example. def embiggen ( str ) str = "#{ str }!!!" str = str.upcase return str end puts( embiggen ('hello world') ) #=> HELLO WORLD!!!. Parts of a method. The name how you will refer to the method. S tick to lowercase letters and underscores. The arguments
E N D
A simple example defembiggen(str) str = "#{str}!!!" str = str.upcase return str end puts( embiggen('hello world') ) #=> HELLO WORLD!!!
Parts of a method • The name • how you will refer to the method. Stick to lowercase letters and underscores. • The arguments • These are the variables, if any, that the method will use or operate on. • The block • the chunk of code that does something • The return value • is what the method passes back to whatever called it – you can think of it as the method's answer.
Add Em defadd_em(name, repeats) (1..repeats).each do |the_name| puts name end end add_em("Jerry",8)
Exercise: Arguments and return Write a method that: • Accepts two strings as arguments • Outputs to screen a string that consists of the two strings concatenated and capitalized • The method should return only the concatenated string
Solution defmush_these_words(str1, str2) return (str1+str2).capitalize end
Scope def foo(var_of_limited_scope) puts "#{var_of_limited_scope} is inside method foo" end foo("hello world") #=> hello world is inside method foo puts var_of_limited_scope #=> NameError: undefined local variable or method `var_of_limited_scope'
DRY • Don’t Repeat Yourself • Methods for things you do often • Keep things modular
require "open-uri" url = "http://www.nytimes.com" pattern = "<img" page = open(url).read tags = page.scan(pattern) puts "The site #{url} has #{tags.length} img tags"
Exercise • Write a method that takes a URL as an argument and returns a count of the number of images. require "open-uri" url = "http://www.nytimes.com" pattern = "<img" page = open(url).read tags = page.scan(pattern) puts "The site #{url} has #{tags.length} img tags"
require "open-uri" defcount_image_tags(url) pattern = "<img" page = open(url).read tags = page.scan(pattern) tags.length end
Can we make it better? • Abstraction
require "open-uri" defcount_any_tags(url, tag) pattern = /<#{tag}\b/ page = open(url).read tags = page.scan(pattern) tags.length end