Reputation: 756
) I am learning ruby via the very good website code School, however in one of their examples I do not understand the method and the logic behind, could someone explain me ?
Thank you so much ;-)
Here is the code
search = "" unless search
games = ["Super Mario Bros.", "Contra", "Metroid", "Mega Man 2"]
matched_games = games.grep(Regexp.new(search))
puts "Found the following games..."
matched_games.each do |game|
puts "- #{game}"
end
I do not really understand line 1 and 3
search = "" unless search
matched_games = games.grep(Regexp.new(search))
Upvotes: 0
Views: 206
Reputation: 3311
Search should be instance of Regexp or nil. In first line search is setting to blank string if it's equal to nil initially.
In third string matched_games is setting to array of strings matched to given regex (http://ruby-doc.org/core-2.0/Enumerable.html#method-i-grep)
Upvotes: 0
Reputation: 38645
The following statement assigns empty string to search
variable if search
is not defined.
search = "" unless search
Had this assignment not be done, Regexp.new
would have thrown an TypeError
with message no implicit conversion of nil into String
, or if search was not defined then NameError
with message undefined local variable or method 'search'...
In the following statement:
matched_games = games.grep(Regexp.new(search))
games.grep(pattern)
returns an array of every element that matches the pattern. For further details please refer to grep. Regexp.new(search)
constructs a new regular expression from the supplied search
variable which can either be a string or a regular expression pattern. Again, for further details please reference Regexp::new
So say for example search is ""
(empty string), then Regexp.new(search)
returns //
, if search = 'Super Mario Bros.' then Regexp.new(search)
returns /Super Mario Bros./
.
Now the pattern matching:
# For search = "", or Regexp.new(search) = //
matched_games = games.grep(Regexp.new(search))
Result: matched_games = ["Super Mario Bros.", "Contra", "Metroid", "Mega Man 2"]
# For search = "Super Mario Bros.", or Regexp.new(search) = /Super Mario Bros./
matched_games = games.grep(Regexp.new(search))
Result: matched_games = ["Super Mario Bros."]
# For search = "something", or Regexp.new(search) = /something/
matched_games = games.grep(Regexp.new(search))
Result: matched_games = []
Hope this makes sense.
Upvotes: 1
Reputation: 24815
vinodadhikary said all. I just don't like the syntax OP mentioned
search = "" unless search
This is nicer
search ||= ""
Upvotes: 0