What does this ruby snippet do? - ruby

As a ruby newbie I am trying to understand a snippet of code in our baseline. Could someone please do that for me ? The snippet appears below
%w{word1 word2}.each { |att| define_method(att.to_sym) { return nil }}

In the context where this line will be run, two methods will be defined
def word1
return nil
end
def word2
return nil
end
For example
class MyClass
%w{word1 word2}.each { |att| define_method(att.to_sym) { return nil }}
end
After my_class.rb file will be loaded you will be able to consume generated methods
test = MyClass.new
test.word1
# or
test.word2

Like jdv said in the comments, for tutorials you might be better of on other websites. Here are all references needed to understand the piece of code provided:
Percent strings, used in %w{word1 word2}
Percent Strings
Besides %(...) which creates a String, the % may
create other types of object. As with strings, an uppercase
letter allows interpolation and escaped characters while a
lowercase letter disables them.
These are the types of percent strings in ruby:
%i: Array of Symbols
%q: String
%r: Regular Expression
%s: Symbol
%w: Array of Strings
%x: Backtick (capture subshell result)
For the two array forms of percent string, if you wish to
include a space in one of the array entries you must escape
it with a “\” character:
%w[one one-hundred\ one]
#=> ["one", "one-hundred one"]
If you are using “(”, “[”, “{”, “<” you must close it with
“)”, “]”, “}”, “>” respectively. You may use most other
non-alphanumeric characters for percent string delimiters
such as “%”, “|”, “^”, etc.
Array#each
each {|item| block} → ary
each → Enumerator
Calls the given block once for each element in self,
passing that element as a parameter. Returns the array
itself.
If no block is given, an Enumerator is returned.
a = [ "a", "b", "c" ]
a.each {|x| print x, " -- " }
produces:
a -- b -- c --
Module#define_method
define_method(symbol, method) → symbol
define_method(symbol) { block } → symbol
Defines an instance method in the receiver. The method
parameter can be a Proc, a Method or an UnboundMethod
object. If a block is specified, it is used as the method
body. This block is evaluated using instance_eval.
class A
def fred
puts "In Fred"
end
def create_method(name, &block)
self.class.define_method(name, &block)
end
define_method(:wilma) { puts "Charge it!" }
end
class B < A
define_method(:barney, instance_method(:fred))
end
a = B.new
a.barney
a.wilma
a.create_method(:betty) { p self }
a.betty
produces:
In Fred
Charge it!
#<B:0x401b39e8>
String#to_sym
to_sym → symbol
Returns the Symbol corresponding to str, creating the
symbol if it did not previously exist. See Symbol#id2name.
"Koala".intern #=> :Koala
s = 'cat'.to_sym #=> :cat
s == :cat #=> true
s = '#cat'.to_sym #=> :#cat
s == :#cat #=> true
This can also be used to create symbols that cannot be
represented using the :xxx notation.
'cat and dog'.to_sym #=> :"cat and dog"

%w{word1 word2} = creating an array that looks like this ['word1', 'word2']
.each = iterating through each value in the array
{} = this is a code block each value in the array will be run through this block
|attr| = block parameter. each value in the array will be placed here
define_method = define a method from the argument
(att.to_sym) = the name of the new method. this will be word1 and then word2
{ return nil } = the body of the new method
So what is happening is you are defining two new methods. One method called word1 and another called word2. Each of these methods will have a body of return nil. They will look like this:
def word1
return nil
end
def word2
return nil
end

Related

Returning the first word in an array that begins with "wa"

I have an array that contains a mixture of strings and symbols.
array = ["candy", :pepper, "wall", :ball, "wacky"]
The aim is to return the first word that begins with the letters "wa".
Here is my code:
def starts_with_wa
deleted_words = array.delete_if{|word| word.class == Symbol}
## deletes the symbols in the original array
deleted_words.find do |w|
##it should iterate through the deleted_Words array but it shows error of undefined local variable or method "array" for main:Object
w.start_with?('wa')
end
end
starts_with_wa
You need to pass the array to your method, otherwise, it is not visible in the scope of the method. Furthermore, I suggest a simple refactoring:
array = ["candy", :pepper, "wall", :ball, "wacky"]
def starts_with_wa(words)
words.find { |word| word.is_a?(String) && word.start_with?('wa') }
end
starts_with_wa(array)
#=> "wall"

How can I create a method that takes a hash (with or without an assigned value) as an argument?

So I am working through test first and am a little stuck. Here is my code so far:
class Dictionary
attr_accessor :entries, :keywords, :item
def initialize
#entries = {}
end
def add(item)
item.each do |words, definition|
#entries[words] = definition
end
end
def keywords
#entries.keys
end
end#class
I am stuck at the rspec test right here:
it 'add keywords (without definition)' do
#d.add('fish')
#d.entries.should == {'fish' => nil}
#d.keywords.should == ['fish']
end
How can I switch my add method around to take either a key/value pair, or just a key with the value set to nil? The first test specifies that the hash is empty when it is created so I cant give it default values there.
One might check the type of the parameter passed to the add method. Whether it’s not an Enumerable, which is apparently a mixin included in Arrays, Hashes etc., just assign it’s value to nil:
def add(item)
case item
when Enumerable
item.each do |words, definition|
#entries[words] = definition
end
else
#entries[item] = nil
end
end
Please note that case uses “case equality” to check argument type.
If you are always passing Strings to the method, you could just have a default value for the second string... Something like the following:
def add(word, definition = nil)
#entries[word] = definition
end
So your code might look something like this:
class Dictionary
attr_accessor :entries, :keywords, :item
def initialize
#entries = {}
end
def add(word, definition = nil)
#entries[word] = definition
end
def keywords
#entries.keys
end
end#class
If you want multiple additions (i.e. add key: "word", with: "many", options: nil), that design might not work for you and you would need to create a solution that would work on the lines of what #mudasobwa suggested. Perhaps:
def add(word, definition = nil)
return #entries[word] = definition unless word.is_a?(Enumerable)
return #entries.update word if word.is_a?(Hash)
raise "What?!"
end
Update, as par request
I updated the method above to allow for words that aren't strings (as you pointed out).
When passing a hash to a method, it is considered as a single parameter.
Key => Value pairs are an implied hash, so when passing a hash to a method, the following are generally the same:
Hash.new.update key: :value
Hash.new.update({key: :value})
Consider the following:
def test(a,b = nil)
puts "a = #{a}"
puts "b = #{b}"
end
test "string"
# => a = string
# => b =
test "string", key: :value, key2: :value2
# => a = string
# => b = {:key=>:value, :key2=>:value2}
test key: :value, key2: :value2, "string"
# Wrong Ruby Syntax due to implied Hash, would raise exception:
# => SyntaxError: (irb):8: syntax error, unexpected '\n', expecting =>
test({key: :value, key2: :value2}, "string")
# correct syntax.
This is why, when you pass add 'fish' => 'aquatic', it's considered only one parameter, a hash - as opposed to add 'fish', 'aquatic' which passes two parameters to the method.
If your method must accept different types of parameters (strings, hashes, numerals, symbols, arrays), you will need to deal with each option in a different way.
This is why #mudasobwa suggested checking the first parameter's type. His solution is pretty decent.
My version is a bit shorter to code, but it runs on the same idea.
def add(word, definition = nil)
return #entries[word] = definition unless word.is_a?(Enumerable)
return #entries.update word if word.is_a?(Hash)
raise "What?!"
end

Ruby puts command in modules returning nil

i am working though LearnTocodethehardway.com http://ruby.learncodethehardway.org/book/ex25.html
On ex25. In the example there is a module that has a bunch of methods that return or print values. The Print_last_word method when supplied with an array of strings just puts nil. it does this even in his example output. My question would then be why?
To be precise, it doesn't puts nil - it puts the last word and returns nil. Here's the example output:
>> Ex25.print_last_word(words)
wait. # <- this is the output
=> nil # <- this is the return value
puts always returns nil.
UPDATE
There seems to be a bug in print_first_word:
module Ex25
def Ex25.print_first_word(words)
word = words.pop(0)
puts word
end
end
Ex25.print_first_word(["foo", "bar", "baz"])
#=> nil
This is because ["foo", "bar", "baz"].pop(0) returns an empty array and puts [] just returns nil without printing anything.
A working implementation (in the exercise's style) could look like this:
module Ex25
def Ex25.print_first_word(words)
word = words.shift
puts word
end
end
To make it more easy to understand:
"puts" never is used for its return value. It is used for its side effect if you wanted a method that would return a word, you would then do something with that word.
words = ["apple", "cucumber", "apple"]
def give_me_first_word(array_of_words)
array_of_words.first
end
variable_to_be_used_later = give_me_first_word(words)
This function would return "apple"(and in this case the variable would be assigned "apple"), but it would puts nothing to the screen. This value would then be used in another program or function.
If you puts a value, you would then not need to return it to any other program as it's already served its purpose. It's actually intuitive because if puts also returned the value, it would be doing two things. The counterpart to "puts" would be "return" that simply returns the value and does not display it to the screen.

How can I write better code for passing key-value arguments?

I want to write code for Ruby in a more Ruby-like style and ran into a problem when working with argument passing.
I have to see if ABC is nil or not. If ABC is nil, I would pass another symbol into dosomething, if not I would pass another type of hash value to compute.
Since Ruby is not like Java, it can pass a different type of argument (different keys).
How can I make the following code more beautiful?
Merging do_manything, do_otherthings, do_manythings_again into a single function is not the answer I because I would call dosomething in many places in my code:
if ABC.nil?
Apple.dosomething (:foo => DEF) { |a|
a.do_manything
a.do_otherthings
a.do_manythings_again
}
else
Apple.dosomething (:bar => ABC) { |a|
a.do_manything
a.do_otherthings
a.do_manythings_again
}
end
Using the ternary operator.
Apple.dosomething (ABC.nil? ? {foo:DEF} : {bar:ABC}) do |a|
a.do_manything
a.do_otherthings
a.do_manythings_again
end
Here is the format
condition ? return_if_true : return_if_false
You can either switch the hash you send:
opts = ABC.nil? ? {foo:DEF} : {bar:ABC}
Apple.dosomething(opts) do |a|
do_many_things
do_other_things
do_many_things_again
end
...or you can pass a lambda as the block:
stuff_to_do = ->(a) do
do_many_things
do_other_things
do_many_things_again
end
if ABC.nil?
Apple.dosomething(foo:DEF,&stuff_to_do)
else
Apple.dosomething(bar:ABC,&stuff_to_do)
end
You could do this:
options = if ABC.nil? then { foo: DEF } else { bar: ABC } end
Apple.do_something options do |apple|
apple.instance_eval do
do_many_things
do_other_things
do_many_things_again
end
end
By convention, words in names and identifiers are separated by underscores (_) and do/end is used for multiple-line blocks.
Also, I believe this question belongs on Code Review.

Special syntax for declaring Ruby objects

Everyone knows two of the ways to create an empty array: Array.new and []. The first one is 'standard', you might say, and the second one is simply syntax sugar. Many different objects such as Hash and maybe even String are shorthanded through this method.
My question is: Is there a way to define my own delimimers for objects? An example would be <>. Maybe an alias like '<' => 'MyObject.new(' and '>' => ')'?
[] is an array literal, {} is a hash literal. There are plenty of these shorthand forms in Ruby. Check this wikibook out for more information.
There is no object literal, but you can use (source):
a = Struct.new(:foo,:bar).new(34,89)
a.foo # 34
a.bar # 89
No. (And ew anyway.) Delimiters are part of the parse process.
You can define operators, like <; that's different than a delimiter. For example, you could redefine < to take a block, and use that block to create a class, or a method, etc. But... I don't think I would.
You could do:
class MyObject; end
def [](*args)
MyObject.new *args
end
# but you can't use it directly:
o = [] #=> [] (empty Array)
# you must to refer to self:
o = self[] #=> #<MyObject:0x1234567>
# but since self depends on where are you, you must assign self to a global variable:
$s = self
o = $s[]
# or to a constant:
S = self
o = S[]
# however, in that case it's better to do it in the proper class:
class << MyObject
def [](*args)
new *args
end
end
# and assign it to a single-letter constant to reduce characters:
S = MyObject
# so
o = S[] #=> #<MyObject:0x1234568>
I can't think on something more compact.

Resources