Presentation is loading. Please wait.

Presentation is loading. Please wait.

CIT 383: Administrative ScriptingSlide #1 CIT 383: Administrative Scripting Methods and Hashes.

Similar presentations


Presentation on theme: "CIT 383: Administrative ScriptingSlide #1 CIT 383: Administrative Scripting Methods and Hashes."— Presentation transcript:

1 CIT 383: Administrative ScriptingSlide #1 CIT 383: Administrative Scripting Methods and Hashes

2 CIT 383: Administrative Scripting Methods: Topics 1.Defining a Method 2.Return Values 3.Arguments 4.Local Variables 5.Meaningful Names

3 CIT 383: Administrative Scripting Defining a Method Methods are defined with the def keyword. def name(arg1, arg2)... end Example def circle_area(radius) Math::PI*radius*radius end

4 CIT 383: Administrative Scripting Return Values Methods return value of last expression irb(main):010:0> def circle_area(radius) irb(main):011:1> Math::PI*radius*radius irb(main):012:1> end => nil irb(main):013:0> area = circle_area(2.1) => 13.854423602331 irb(main):014:0> area2 = circle_area(10) => 314.159265358979

5 CIT 383: Administrative Scripting The return statement The return statement causes function to return immediately with specified value. This is useful to handle special cases as in the following examples: def circle_area(radius) return 0 if radius < 0 Math::PI*radius*radius end or def factorial(n) return 1 if n == 1 n * factorial(n-1) end

6 Method Examples irb(main):037:0> def horizontalrule(length) irb(main):038:1> '-' * length irb(main):039:1> end => nil irb(main):040:0> horizontalrule(20) => "--------------------" irb(main):041:0> horizontalrule(30) => "------------------------------" irb(main):042:0> def truncate_string_to_20(mystring) irb(main):043:1> mystring[0, 20] irb(main):044:1> end => nil irb(main):045:0> truncate_string_to_20('abcdefghijklmnopqrstuvwxyz') => "abcdefghijklmnopqrst" irb(main):046:0> truncate_string_to_20(horizontalrule(30)) => "--------------------" irb(main):047:0> truncate_string_to_20(horizontalrule(40)) => "--------------------"

7 Multiple Return Values irb(main):028:0> def firstlast(comma_string) irb(main):029:1> fields = comma_string.split(',') irb(main):030:1> return fields[0], fields[-1] irb(main):031:1> end => nil irb(main):032:0> mystring = 'field1,field2,field3,field4,field5,field6' => "field1,field2,field3,field4,field5,field6" irb(main):033:0> myfields = firstlast(mystring) => ["field1", "field6"] irb(main):034:0> myfields[0] => "field1" irb(main):035:0> myfields[1] => "field6" If you know how many values are returned from a method, you can assign them to individual variables instead of an array using the following technique, which makes for much more readable code: irb(main):036:0> firstfield, lastfield = firstlast(mystring) => ["field1", "field6"] CIT 383: Administrative Scripting

8 Using one value as error indicator def celcius2farenheit(celcius_temp) if celcius_temp < -273.15 return -1, “Impossible temperature” else return 0, 32 + 1.8*celcius_temp end error, farenheit_temp = celcius2farenheit(celcius) if error == -1 puts “Conversion error: #{farenheit}” else puts “The temperature is #{farenheit} degrees F.” end

9 CIT 383: Administrative Scripting Arguments Methods take zero or more named arguments def noargument def oneargument(arg1) def twoarguments(arg1, arg2) Variable number of arguments Last argument must be prefixed by a * def csv_list(*values) values.join(“, “) end comma_sep_list = csv_list(4,5,6)# “4, 5, 6”

10 Multiple Argument Examples irb(main):051:0> def truncate(mystring, length) irb(main):052:1> mystring[0, length] irb(main):053:1> end => nil irb(main):054:0> truncate('abcdefghijklmnopqrstuvwxyz', 10) => "abcdefghij" irb(main):055:0> truncate('abcdefghijklmnopqrstuvwxyz', 20) => "abcdefghijklmnopqrst" irb(main):056:0> truncate('abcdefghijklmnopqrstuvwxyz', -1) => nil irb(main):057:0> def rectangle_area(x, y) irb(main):058:1> x*y irb(main):059:1> end => nil irb(main):061:0> rectangle_area(3,4) => 12 CIT 383: Administrative Scripting

11 Wrong Number of Arguments irb(main):062:0> rectangle_area(1) ArgumentError: wrong number of arguments (1 for 2) from (irb):62:in `rectangle_area' from (irb):62 from :0 irb(main):063:0> rectangle_area(1, 2, 3) ArgumentError: wrong number of arguments (3 for 2) from (irb):63:in `rectangle_area' from (irb):63 from :0 irb(main):064:0> rectangle_area(5,6) => 30 CIT 383: Administrative Scripting

12 Default Arguments Optional default values for arguments def truncate(mystring, length=1) mystring[0, length] end If default exists, do not need to specify arg truncate(“ruby”, 3) # “rub” truncate(“ruby”, 1) # “r” truncate(“ruby”) # “r”

13 CIT 383: Administrative Scripting Default Arguments Default values can be expressions def suffix(str, index=str.size-1) str[index, str.size-index] end Suffix returns final substring starting at index suffix(“ruby”, 1) # “uby” suffix(“ruby”, 3) # “y” suffix(“ruby”) # “y”

14 CIT 383: Administrative Scripting Local Variables Local variable: A variable defined within a method, block, or loop. Scope: Where a variable can be used. The scope of a local variable starts from its definition and continues to the keyword (usually end ) terminating the block, method, or loop. Global variable: A variable accessible anywhere in the program. A global variable’s name must begin with $.

15 CIT 383: Administrative Scripting Local Variables $ irb > def set_variable(value) >var = value > $global_var = value > puts “var set to #{var}” > end > > set_variable(10) > puts $global_var 10 > puts var NameError: undefined local variable or method `var' for main:Object

16 CIT 383: Administrative Scripting Method Names Method names begin with a letter –Method names may contain letters, numbers, _ –Method names may end with a ? or ! Special method names –Setter method names end with an = –Operator methods Named for and act like operators. Examples: +, -, **, >=, &&

17 CIT 383: Administrative Scripting Meaningful Names Use intention-revealing names –Bad: d = 8 # d is days since last login –Better: days_since_login = 8 Avoid disinformation –Ex: give plural objects plural names –character = ?a –characters = Array.new

18 CIT 383: Administrative Scripting Meaningful Names Use searchable names –Long enough names to search for. –Use named constants instead of magic numbers. –Restrict single-letter names to local variables. Use pronounceable names –Easier to communicate with others.

19 CIT 383: Administrative Scripting Meaningful Names Use verbs in method names –save –save_quota_data Pick one word per concept –delete –remove –expunge –kill

20 CIT 383: Administrative Scripting Writing Methods Do one thing –A method should do one and only one task. Indent –Indent the body of a method by one tab. –Keep level of indenting low; if you find more than two levels of indentation within a method, break it into multiple methods. Keep it small –Always less than one page. –2-12 lines is typical of a good method.

21 CIT 383: Administrative Scripting Hashes: Topics 1.What is a Hash? 2.Creating Hashes 3.Hash Keys 4.Accessing Hashes 5.Hash Methods 6.Iterators 7.Hashes and Ordering 8.Multi-valued hashes 9.What are hashes good for?

22 CIT 383: Administrative Scripting What is a Hash? A hash is a dictionary, associating keys with values. 192.122.237.230 kosh.nku.edu www.nku.edu 192.122.237.7 google.com 64.233.167.99 Hashes are also called  Associative arrays  Dictionaries  Maps

23 CIT 383: Administrative Scripting Creating a Hash Creating a Hash literal numbers = { ‘one’ => 1, ‘two’ => 2, ‘three’ => 3 } Creating a Hash element by element numbers = Hash.new numbers[‘one’] = 1 numbers[‘two’] = 2 numbers[‘three’] = 3

24 CIT 383: Administrative Scripting Hash Keys Almost any ruby object can be a key  Integers  Floats  Strings  Arrays  Symbols Symbols are the fastest hash key  Similar to strings, but cannot be changed.  Written with colon prefix-- :one, :two, :three

25 CIT 383: Administrative Scripting Accessing Hash Items Indexing (fast) numbers[‘one’] # 1 Reverse indexing (slow) numbers.index(1) # ‘one’ Keys numbers.keys#[‘one’,’two’,’three’] Values numbers.values# [1,2,3]

26 CIT 383: Administrative Scripting Hash.methods Deletion numbers.delete(‘three’) # 3 numbers # [‘one’,’two’] Empty numbers.empty?# false {}.empty? # true Size numbers.length# 2

27 CIT 383: Administrative Scripting Hash Iterators Iterate over keys numbers = {:two=>2, :three=>3, :one=>1} numbers.each_key do |key| puts “#{key} has value #{numbers[key]}” end Iterate over values numbers.each_value do |value| puts “#{value} has key #{numbers.index(value)” end

28 CIT 383: Administrative Scripting Hash Iterators Iterate over keys and values numbers.each do |key,val| puts “#{key} has value #{val}” end

29 CIT 383: Administrative Scripting Hashes and Ordering Hashes are not ordered like an array Output of iterator may be: two, three, one Solution: 1.Get array of keys. 2.Sort array of keys. 3.Iterate over array of keys. 4.Use hash[] index to get values. Code: numbers.keys.sort.each do |key| puts “#{key} has value #{numbers[key]}” end

30 CIT 383: Administrative Scripting Multi-valued hashes What can you do if a key has many values? Use arrays as the values host2ip[‘www.nku.edu’] = [‘192.122.237.7’] host2ip[‘google.com’] = [ ’64.233.167.99’, ’64.233.187.99’, ’72.14.207.99’] host2ip[‘www.nku.edu’][0] host2ip[‘google.com’][1]

31 CIT 383: Administrative Scripting What are hashes good for? Mapping one data item to another Characters to ASCII values Hostnames to IP addresses Fast, easy lookups To lookup an item in array primes = [2,3,5,7,9,11] primes.each do |num| puts “Found it” if num == 2 end To lookup an item in a hash primes = [2=>1,3=>1,5=>1,7=>1,9=>1,11=>1] puts “Found it” if numbers[2] Implementing sparse data sets zip = { 41099=>’NKU’, 41076=>’HH’, 43606=>’UT’}

32 CIT 383: Administrative ScriptingSlide #32 References 1.Michael Fitzgerald, Learning Ruby, O’Reilly, 2008. 2.David Flanagan and Yukihiro Matsumoto, The Ruby Programming Language, O’Reilly, 2008. 3.Hal Fulton, The Ruby Way, 2 nd edition, Addison- Wesley, 2007. 4.Robert C. Martin, Clean Code, Prentice Hall, 2008. 5.Dave Thomas with Chad Fowler and Andy Hunt, Programming Ruby, 2 nd edition, Pragmatic Programmers, 2005.


Download ppt "CIT 383: Administrative ScriptingSlide #1 CIT 383: Administrative Scripting Methods and Hashes."

Similar presentations


Ads by Google