- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Ruby hashes
This part of the Ruby tutorial will mention Ruby hashes. A hash is a collection of key-value pairs. It is similar to an array. Unlike arrays, hashes can have arbitrary objects as indexes. Arrays have can only have integers. Hashes are sometimes called associated arrays.
Hashes are powerful collections. They have many methods that programmers can use to do their work.
Hash creation
A hash can be created in two basic ways: with the new
keyword or with the hash literal.
#!/usr/bin/ruby names = Hash.new names[1] = "Jane" names[2] = "Thomas" puts names
The first script creates a hash and adds two key-value pairs into the hash object.
names = Hash.new
A hash object is created.
names[1] = "Jane" names[2] = "Thomas"
We add two pairs of values to the hash. The numbers 1, 2 are the keys to the hash. The keys are placed inside the square brackets. The names are the values that belong to the keys.
puts names
The puts
method prints the string representation of the hash to the console. It is also the string literal of the hash.
$ ./create.rb {1=>"Jane", 2=>"Thomas"}
From the output we can see the literal representation of the names hash. A hash is bounded by curly brackets. The keys and the values are paired with the =>
characters.
A store
method can be used to initialize the hash with some values. It can be use instead of the square brackets.
#!/usr/bin/ruby names = Hash.new names.store(1, "Jane") names.store(2, "Thomas") names.store(3, "Rebecca") puts names
We have a similar script. This time we use the store
method. The method associates the given key with the given value and stores the pair in the hash.
names.store(1, "Jane")
The first parameter of the store
method is the key and the second parameter is the value.
In the third script, we create a hash with the hash literal notation. The values are bound by the curly brackets. And the key-value pairs are associated with the =>
characters.
#!/usr/bin/ruby domains = { "de" => "Germany", "sk" => "Slovakia", "hu" => "Hungary", "us" => "United States", "no" => "Norway" } puts domains["de"] puts domains["sk"]
We create a domains hash with 5 pairs. This time both keys and values are string types.
domains = { "de" => "Germany", "sk" => "Slovakia", "hu" => "Hungary", "us" => "United States", "no" => "Norway" }
This is a hash literal notation. The key-value pairs are put between the curly brackets. The items are separated by the comma character. And the keys are associated with values using the =>
characters combination.
puts domains["de"]
Here we print the domain value name associated with the "de" key.
$ ./create3.rb Germany Slovakia
This is the output of the code example.
Basic work
In this section, we present some methods for the very basic work with Ruby hashes.
#!/usr/bin/ruby names = Hash.new names[1] = "Jane" names[2] = "Thomas" names[3] = "Robert" names[4] = "Julia" names[5] = "Rebecca" puts "The size of the hash is #{names.size}" puts names.keys.inspect puts names.values.inspect
In the above Ruby script, we create a hash with five values. We introduce three hash methods.
puts "The size of the hash is #{names.size}"
The size
method returns the size of the hash. It is a synonym for the length
method.
puts names.keys.inspect puts names.values.inspect
The keys
method returns all keys of the hash. In a similar fashion, the values
method returns all the values of the hash. The returned data is in the form of an array. To have a more readable output, we also call the inspect
method on the returned arrays.
$ ./basic.rb The size of the hash is 5 [1, 2, 3, 4, 5] ["Jane", "Thomas", "Robert", "Julia", "Rebecca"]
We see the output of the example. Note that the output of the last two methods are two arrays.
The second example of the section presents three distinct hash methods.
#!/usr/bin/ruby names1 = Hash.new names1[1] = "Jane" names1[2] = "Thomas" names1[3] = "Robert" names1[4] = "Julia" names1[5] = "Rebecca" names2 = names1.dup puts names1.eql? names2 puts names1.empty? names1.clear puts names1.empty?
The Ruby script creates a names hash. It calls three hash methods on the object.
names2 = names1.dup
We create a duplicate of the hash by calling the dup
method. The method is inherited by the hash from the parent object.
puts names1.eql? names2
The eql?
method compares two hash objects. In our case the hashes are equal and the line prints true.
puts names1.empty?
The empty?
method checks whether the hash is empty or not. The line print false because the names1 hash has five items.
names1.clear puts names1.empty?
The clear
method deletes all items from the hash. The successive call of the empty?
method returns true.
$ ./basic2.rb true false true
This is the example output.
We have methods that can determine whether a key or a value is present in the hash.
#!/usr/bin/ruby domains = { :de => "Germany", :sk => "Slovakia", :no => "Norway", :us => "United States" } puts domains.has_key? :de puts domains.include? :no puts domains.key? :me puts domains.member? :sk puts domains.has_value? "Slovakia" puts domains.value? "Germany"
We create a domains hash with four pairs. The keys are symbols. Symbols are often used as keys, because they are more efficient.
puts domains.has_key? :de puts domains.include? :no puts domains.key? :me puts domains.member? :sk
Here we have four methods that determine whether a key is in the hash. They all do the same; they are synonyms.
puts domains.has_value? "Slovakia" puts domains.value? "Germany"
These two methods check if the two strings are inside the hash.
$ ./has.rb true true false true true true
This is the output of the example.
In the final example of the section, we will read values from the hash.
#!/usr/bin/ruby stones = { 1 => "garnet", 2 => "topaz", 3 => "opal", 4 => "amethyst" } puts stones.fetch 1 puts stones[2] puts stones.values_at 1, 2, 3
The Ruby script presents three hash methods for reading values of a hash.
puts stones.fetch 1
The fetch
method reads a value for a given key.
puts stones[2]
Square brackets can be used to get a value. In our case, the line prints "topaz" to the console.
puts stones.values_at 1, 2, 3
The values_at
method can be used to get multiple values at one step. The method returns an array of the values for the given keys.
$ ./read.rb garnet topaz garnet topaz opal
This is the output of the example.
Looping through a hash
There are several methods that can be used to loop through a Ruby hash.
#!/usr/bin/ruby stones = { 1 => "garnet", 2 => "topaz", 3 => "opal", 4 => "amethyst" } stones.each { |k, v| puts "Key: #{k}, Value: #{v}" } stones.each_key { |key| puts "#{key}" } stones.each_value { |val| puts "#{val}" } stones.each_pair { |k, v| puts "Key: #{k}, Value: #{v}" }
In the above example, we present four methods. We use them to display all keys, values and both keys and values of a hash.
stones.each { |k, v| puts "Key: #{k}, Value: #{v}" }
The each
method calls the given block for each key in the hash, passing key-value pair as parameter.
stones.each_key { |key| puts "#{key}" }
We use the each_key
method to loop throug all keys of a hash. They are printed to the console.
stones.each_value { |val| puts "#{val}" }
The each_value
can be used to loop throug the values of a hash.
stones.each_pair { |k, v| puts "Key: #{k}, Value: #{v}" }
The each_pair
method is a synonym for the each
method. We loop through the keys and values of the stones hash.
$ ./loop.rb Key: 1, Value: garnet Key: 2, Value: topaz Key: 3, Value: opal Key: 4, Value: amethyst 1 2 3 4 garnet topaz opal amethyst Key: 1, Value: garnet Key: 2, Value: topaz Key: 3, Value: opal Key: 4, Value: amethyst
The output shows the keys and values, keys, values of the stones hash.
Deleting pairs
In the following examples, we will concern ourselves with methods that delete pairs from the hashes. This includes methods that delete individual pairs as well as methods that can delete multiple key-values at one step.
#!/usr/bin/ruby names = Hash.new names[1] = "Jane" names[2] = "Thomas" names[3] = "Robert" names[4] = "Julia" names[5] = "Rebecca" names.delete 4 names.shift puts names
In the script we have two methods: delete
and shift
. The delete
method removes and returns a value for a specified key. The shift
method deletes the first pair from the hash. It also returns the removed pair as an array.
names.delete 4
Here we delete a pair 4 => "Julia".
names.shift
This code line removes the first pair, namely 1 => "Jane".
$ ./deleteitem.rb {2=>"Thomas", 3=>"Robert", 5=>"Rebecca"}
In the output we can see the pairs of the hash that are left.
The reject
and the delete_if
methods can remove multiple pairs from a hash. The methods delete pairs that return true for the given condition in the block. There is an important distinction between the two methods. The reject
method works on a copy of a hash while the delete_if
works on the original hash.
#!/usr/local/bin/ruby names1 = Hash.new names1[1] = "Jane" names1[2] = "Thomas" names1[3] = "Robert" names1[4] = "Julia" names1[5] = "Rebecca" puts names1.reject { |k, v| v =~ /R.*/ } puts names1 puts names1.delete_if { |k, v| k<=3 } puts names1
The example deletes multiple pairs using the previously mentioned methods.
puts names1.reject { |k, v| v =~ /R.*/ }
The reject
method removes all values that fit the regular expression in the block. The modified hash is returned and the original hash is not changed.
puts names1
The output of this line confirms that the original hash was intact.
puts names1.delete_if { |k, v| k<=3 }
In this case, we delete all pairs, for which the key is lower or equal to 3. The method modifies the original hash.
$ ./massdelete.rb {1=>"Jane", 2=>"Thomas", 4=>"Julia"} {1=>"Jane", 2=>"Thomas", 3=>"Robert", 4=>"Julia", 5=>"Rebecca"} {4=>"Julia", 5=>"Rebecca"} {4=>"Julia", 5=>"Rebecca"}
Output of the example.
Adding hashes
Ruby's merge and update methods add (key, value) pairs to hashes. Ruby has methods for hash addition.
#!/usr/bin/ruby names1 = Hash.new names1[1] = "Jane" names1[2] = "Thomas" names2 = Hash.new names2[3] = "Robert" names2[4] = "Julia" names = names1.merge names2 puts names names = names1.update names2 puts names
In the Ruby script, we create two hashes. Then we apply merge
and update
methods on them.
names = names1.merge names2 puts names
The names1 and names2 hashes are combined. The result is assigned to the names hash. We print the newly created hash.
$ ./merge.rb {1=>"Jane", 2=>"Thomas", 3=>"Robert", 4=>"Julia"} {1=>"Jane", 2=>"Thomas", 3=>"Robert", 4=>"Julia"}
As we can see, the final hashes contain pairs from the names1
and names2
hashes.
The merge vs merge!
In the final section, we recap a common Ruby idiom. Several Ruby methods have counterparts that end with an exclamation point. This mark, which has no syntactic significance, indicates that a method modifies the object on which that method is called.
#!/usr/bin/ruby names1 = Hash.new names1[1] = "Jane" names1[2] = "Thomas" names2 = Hash.new names2[3] = "Robert" names2[4] = "Julia" names = names1.merge names2 puts names puts names1 names = names1.merge! names2 puts names puts names1
We will demonstrate the difference on the merge
and merge!
methods.
names = names1.merge names2
The merge
does not modify the names1
hash. It works on its copy.
names = names1.merge! names2
The merge!
method works on the original hash. The names1
hash is changed.
$ ./merge2.rb {1=>"Jane", 2=>"Thomas", 3=>"Robert", 4=>"Julia"} {1=>"Jane", 2=>"Thomas"} {1=>"Jane", 2=>"Thomas", 3=>"Robert", 4=>"Julia"} {1=>"Jane", 2=>"Thomas", 3=>"Robert", 4=>"Julia"}
This is the output of the merge2.rb
program.
In this chapter, we worked with Ruby hashes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论