It shows that you are unregistered. Please register with us by clicking Here
![]() |
|
![]() |
![]() | Register - FAQ - Today's Posts - New Posts - Support - Search | ![]() |
|
|
#1 (permalink) |
|
Member
Join Date: Jul 2006
Age: 25
Posts: 53
|
Some basic Ruby code:
# Everything, including literals, is an object, so this works:-199.abs # 199"ruby is cool".length # 12"Rick".index("c") # 2"Nice Day Isn't It?".split(//).uniq.sort.join # " '?DINaceinsty"Collections Constructing and using an array: a = [1, 'hi', 3.14, 1, 2, [4, 5]]a[2] # 3.14a.reverse # [[4, 5], 2, 1, 3.14, 'hi', 1]a.flatten.uniq # [1, 'hi', 3.14, 2, 4, 5] Constructing and using a hash: hash = {:water => 'wet', :fire => 'hot'}puts hash[:fire] # Prints: hothash.each_pair do |key, value| puts "#{key} is #{value}"end# Prints: water is wet# fire is hothash.delete_if {|key, value| key == :water} # Deletes :water => 'wet'[edit] Blocks and iterators The two syntaxes for creating a code block: { puts "Hello, World!" }do puts "Hello, World!" end Passing a block as a parameter (to be a closure): def remember(&p) @block = pend# Invoke the method, giving it a block that takes a name.remember {|name| puts "Hello, #{name}!"}# When the time is right -- call the closure!@block.call("John")# Prints "Hello, John!" Returning closures from a method: def foo(initial_value=0) var = initial_value return Proc.new {|x| var = x}, Proc.new { var }endsetter, getter = foosetter.call(21)getter.call # => 21Yielding program flow to a block provided at the location of the call: def bfs(e) q = [] e.mark yield e q.push e while not q.empty? u = q.shift u.edge_iterator do |v| if not v.marked? v.mark yield v q.push v end end endendbfs(e) {|v| puts v}Iterating over enumerations and arrays using blocks: a = [1, 'hi', 3.14]a.each {|item| puts item} # Prints each element(3..6).each {|num| puts num} # Prints the numbers 3 through 6[1,3,5].inject(0) {|sum, element| sum+element} # 9, (you can pass both a parameter and a block)Blocks work with many built-in methods: File.open('file.txt', 'w+b') do |file| file.puts 'Wrote some text.'end # File automatically closed hereOr: File.readlines('file.txt').each do |line| # Process each line, here.endUsing an enumeration and a block to square 1 to 10: (1..10).collect {|x| x*x} => [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] |
|
|
|
|
|
![]() |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Ruby programming language | Ankita | Programming | 1 | 08-19-2006 09:27 PM |
| Ruby On Rails | imehesz | Website Design | 2 | 07-20-2006 03:22 AM |
| I miss Ruby | imehesz | preCharge Central | 0 | 07-06-2006 03:24 AM |
| |Ruby Darkness| | Carnage | Graphics & Multimedia | 10 | 06-20-2006 04:27 PM |
| I'm New -- Some Examples | moronofdread | Graphics & Multimedia | 11 | 07-29-2005 08:18 PM |