Why doesn't this example ruby code print the result? - ruby

I'm wondering why the code below doesn't print the movies that have more than 3 stars.
movie_ratings = {
memento: 3,
primer: 3.5,
the_matrix: 5,
truman_show: 4,
red_dawn: 1.5,
skyfall: 4,
alex_cross: 2,
uhf: 1,
lion_king: 3.5
}
def good_movies
puts movie_ratings.select {|movies, ratings| ratings > 3}
end
good_movies

Local variable movie_ratings is not accessible in the method good_movies. Several approaches are available here:
Pass ratings as a parameter
movie_ratings = {
memento: 3,
primer: 3.5,
the_matrix: 5,
truman_show: 4,
red_dawn: 1.5,
skyfall: 4,
alex_cross: 2,
uhf: 1,
lion_king: 3.5
}
def good_movies(ratings)
puts ratings.select {|movies, ratings| ratings > 3}
end
good_movies(movie_ratings)
Make ratings instance variable (instead of local variable)
#movie_ratings = {
memento: 3,
primer: 3.5,
the_matrix: 5,
truman_show: 4,
red_dawn: 1.5,
skyfall: 4,
alex_cross: 2,
uhf: 1,
lion_king: 3.5
}
def good_movies
puts #movie_ratings.select {|movies, ratings| ratings > 3}
end
good_movies

The variable movie_ratings is not in the scope of the method. you should pass it as a parameter:
movie_ratings = {
memento: 3,
primer: 3.5,
the_matrix: 5,
truman_show: 4,
red_dawn: 1.5,
skyfall: 4,
alex_cross: 2,
uhf: 1,
lion_king: 3.5
}
def good_movies movie_ratings
puts movie_ratings.select {|movies, ratings| ratings > 3}
end
good_movies movie_ratings
# {:primer=>3.5, :the_matrix=>5, :truman_show=>4, :skyfall=>4, :lion_king=>3.5}

Because local variables cannot take scope into a method block. Change it to another type of variable, for example an instance variable, and it will work.
#movie_ratings = {
memento: 3,
primer: 3.5,
the_matrix: 5,
truman_show: 4,
red_dawn: 1.5,
skyfall: 4,
alex_cross: 2,
uhf: 1,
lion_king: 3.5
}
def good_movies
puts #movie_ratings.select {|movies, ratings| ratings > 3}
end
good_movies

You should either pass movie_ratings to the method good_movies like this :
def good_movies(movie_ratings)
puts movie_ratings.select {|movies, ratings| ratings > 3}
end
or make movie_ratings an instance variable like this:
#movie_ratings
and then inside the method use: puts #movie_ratings.select {|movies, ratings| ratings > 3}

If you're getting the following error:
NameError: undefined local variable or method `movie_ratings' for main:Object
The reason is the method good_movies creates its own local scope, and it doesn't understand what movie_ratings is. You need to pass it to the method so that the method will understand what it is.
def good_movies(movies)
return movies.select { |m, r| r > 3 }
end

Related

How to create a function in Ruby that take a average of an array?

I tried something like this:
def average_array_float(&array)
array.inject{ |sum, el| sum + el }.to_f / array.size
end
no success
array = [1, 2, 3]
def even_numbers(array)
array.select { |num| num.even? }
end
p array.even_numbers
reply:
$ bundle exec ruby main.rb
Traceback (most recent call last):
main.rb:7:in `<main>': private method `even_numbers' called for [1, 2, 3]:Array (NoMethodError)
exit status 1
what i am doing wrong?
You have to pass the array to the method:
def even_numbers(array)
array.select { |num| num.even? }
end
array = [1, 2, 3, 4, 5, 6]
even_numbers(array)
#=> [2, 4, 6]
The NoMethodError in your example happens because if you define a method on the top-level, it becomes a private method of Object:
Object.private_methods
#=> [:initialize, :inherited, :method_added, :method_removed, :method_undefined,
# :remove_const, :initialize_copy, :initialize_clone, :using, :public,
# :ruby2_keywords, :protected, :private, :included, :extended, :prepended,
# :even_numbers, :sprintf, :format, ...]
# ^^^^^^^^^^^^^
And since array is an Object, it can access that method (privately).
If you really wanted to add the method to Array, you could open the corresponding class:
class Array
def even_numbers
select { |num| num.even? }
end
end
Which gives you:
[1, 2, 3, 4, 5, 6].even_numbers
#=> [2, 4, 6]
However, although this works, it's not advised to alter objects that are not your own, let alone Ruby's core classes.
Regarding your other method, you could use sum and fdiv:
def average(array)
array.sum.fdiv(array.size)
end
average([1, 2, 4])
#=> 2.3333333333333335
Or quo if you prefer a precise result:
def average(array)
array.sum.quo(array.size)
end
average([1, 2, 4])
#=> (7/3)

How to pass arguments directy to a class without calling new method?

In Ruby a Hash can be created by:
Hash(a: 5, b: 6)
An Array can be created like this:
Array(100)
Sets can be created with the code:
require 'set'
Set[1,2,3]
So, how can I define a class that can accept arguments without calling the initialize method?
So, how can I define a class that can accept arguments without calling the initialize method?
You can't. In your examples, Hash and Array are actually methods.
And example with Set uses Set::[], naturally. And so it's not any different from any other class method that returns you instances of that class. For instance, User::create (or what-have-you).
In Ruby a Hash can be created by:
Hash(a: 5, b: 6)
Hash() is actually a method of the Kernel module:
p defined?(Hash()) # => "method"
p defined?(Kernel.Hash()) # => "method"
But without parentheses, Hash, Array, String, etc. all are just classes:
defined?(Hash) # => "constant"
defined?(Array) # => "constant"
In Ruby 2.6.3, the same goes for Arrays(), Complex(), Float(), Hash(), Integer(), Rational(), String(), and URI() - they all are methods.
But Set is a class:
require 'set'
p defined?(Set) # => "constant"
p set = Set[1,2,3] # => #<Set: {1, 2, 3}>
p set.to_a # => [1, 2, 3]
So, Set[1,2,3] is actually calling the [] method of Set. It looks kind of like this:
class Something
def initialize(*a)
#hash = {}
a.each { |v| #hash.store(v, nil) }
end
def self.[](*a) new(*a) end
define_method(:to_a) { #hash.keys }
define_method(:inspect) { "#<#{self.class}: {#{#hash.keys.to_s[1..-2]}}>" }
alias :to_s :inspect
end
p defined?(Something) # => "constant"
p set = Something[1,2,3] # => #<Something: {1, 2, 3}>
p set1 = Something[[1, 2, 3], 2, 2, 3, 4, {4 => :a}, 5] # => #<Something: {[1, 2, 3], 2, 3, 4, {4=>:a}, 5}>
p set.to_a # => [1, 2, 3]
p set1.to_a # => [[1, 2, 3], 2, 3, 4, [4, 4], 5]
Back to the question:
So, how can I define a class that can accept arguments without calling
the initialize method?
I don't think it's possible!

Selecting from a Hash

I'm learning Ruby on Codecademy and I'm having trouble with this problem:
Create a new variable, good_movies, and set it equal to the result of
calling .select on movie_ratings, selecting only movies with a rating
strictly greater than 3.
Here's my code:
movie_ratings = {
memento: 3,
primer: 3.5,
the_matrix: 5,
truman_show: 4,
red_dawn: 1.5,
skyfall: 4,
alex_cross: 2,
uhf: 1,
lion_king: 3.5
}
# Add your code below!
good_movies = movie_ratings.each {|k,v| v > 3}
Here is the result:
{:memento=>3, :primer=>3.5, :the_matrix=>5, :truman_show=>4, :red_dawn=>1.5, :skyfall=>4, :alex_cross=>2, :uhf=>1, :lion_king=>3.5}
And this is the error that I'm getting:
Oops, try again. It looks like good_movies includes memento, but it
shouldn't.
"memento" has a value of 3 and I thought that my "v > 3" condition would filter it out; what am I doing wrong?
Use Hash#select to filter as per conditions, not Hash#each.
movie_ratings.select {|k,v| v > 3}
Basically Hash#each returns the receiver on which you called it, and in your case, it the original hash movie_ratings. Indeed it contains memento key, as I said, Hash#each not for filtering purposes. But Hash#select, will filter memento with its value out from the output Hash, thus your code will not give any objections.
You must have change each for select like this: good_movies = movie_ratings.select {|k,v| v > 3}

Can you supply arguments to the map(&:method) syntax in Ruby?

You're probably familiar with the following Ruby shorthand (a is an array):
a.map(&:method)
For example, try the following in irb:
>> a=[:a, 'a', 1, 1.0]
=> [:a, "a", 1, 1.0]
>> a.map(&:class)
=> [Symbol, String, Fixnum, Float]
The syntax a.map(&:class) is a shorthand for a.map {|x| x.class}.
Read more about this syntax in "What does map(&:name) mean in Ruby?".
Through the syntax &:class, you're making a method call class for each array element.
My question is: can you supply arguments to the method call? And if so, how?
For example, how do you convert the following syntax
a = [1,3,5,7,9]
a.map {|x| x + 2}
to the &: syntax?
I'm not suggesting that the &: syntax is better.
I'm merely interested in the mechanics of using the &: syntax with arguments.
I assume you know that + is a method on Integer class. You can try the following in irb:
>> a=1
=> 1
>> a+(1)
=> 2
>> a.send(:+, 1)
=> 2
You can create a simple patch on Symbol like this:
class Symbol
def with(*args, &block)
->(caller, *rest) { caller.send(self, *rest, *args, &block) }
end
end
Which will enable you to do not only this:
a = [1,3,5,7,9]
a.map(&:+.with(2))
# => [3, 5, 7, 9, 11]
But also a lot of other cool stuff, like passing multiple parameters:
arr = ["abc", "babc", "great", "fruit"]
arr.map(&:center.with(20, '*'))
# => ["********abc*********", "********babc********", "*******great********", "*******fruit********"]
arr.map(&:[].with(1, 3))
# => ["bc", "abc", "rea", "rui"]
arr.map(&:[].with(/a(.*)/))
# => ["abc", "abc", "at", nil]
arr.map(&:[].with(/a(.*)/, 1))
# => ["bc", "bc", "t", nil]
And even work with inject, which passes two arguments to the block:
%w(abecd ab cd).inject(&:gsub.with('cde'))
# => "cdeeecde"
Or something super cool as passing [shorthand] blocks to the shorthand block:
[['0', '1'], ['2', '3']].map(&:map.with(&:to_i))
# => [[0, 1], [2, 3]]
[%w(a b), %w(c d)].map(&:inject.with(&:+))
# => ["ab", "cd"]
[(1..5), (6..10)].map(&:map.with(&:*.with(2)))
# => [[2, 4, 6, 8, 10], [12, 14, 16, 18, 20]]
Here is a conversation I had with #ArupRakshit explaining it further:
Can you supply arguments to the map(&:method) syntax in Ruby?
As #amcaplan suggested in the comment below, you could create a shorter syntax, if you rename the with method to call. In this case, ruby has a built in shortcut for this special method .().
So you could use the above like this:
class Symbol
def call(*args, &block)
->(caller, *rest) { caller.send(self, *rest, *args, &block) }
end
end
a = [1,3,5,7,9]
a.map(&:+.(2))
# => [3, 5, 7, 9, 11]
[(1..5), (6..10)].map(&:map.(&:*.(2)))
# => [[2, 4, 6, 8, 10], [12, 14, 16, 18, 20]]
Here is a version using Refinements (which is less hacky than globally monkey patching Symbol):
module AmpWithArguments
refine Symbol do
def call(*args, &block)
->(caller, *rest) { caller.send(self, *rest, *args, &block) }
end
end
end
using AmpWithArguments
a = [1,3,5,7,9]
a.map(&:+.(2))
# => [3, 5, 7, 9, 11]
[(1..5), (6..10)].map(&:map.(&:*.(2)))
# => [[2, 4, 6, 8, 10], [12, 14, 16, 18, 20]]
For your example can be done a.map(&2.method(:+)).
Arup-iMac:$ pry
[1] pry(main)> a = [1,3,5,7,9]
=> [1, 3, 5, 7, 9]
[2] pry(main)> a.map(&2.method(:+))
=> [3, 5, 7, 9, 11]
[3] pry(main)>
Here is how it works :-
[3] pry(main)> 2.method(:+)
=> #<Method: Fixnum#+>
[4] pry(main)> 2.method(:+).to_proc
=> #<Proc:0x000001030cb990 (lambda)>
[5] pry(main)> 2.method(:+).to_proc.call(1)
=> 3
2.method(:+) gives a Method object. Then &, on 2.method(:+), actually a call #to_proc method, which is making it a Proc object. Then follow What do you call the &: operator in Ruby?.
As the post you linked to confirms, a.map(&:class) is not a shorthand for a.map {|x| x.class} but for a.map(&:class.to_proc).
This means that to_proc is called on whatever follows the & operator.
So you could give it directly a Proc instead:
a.map(&(Proc.new {|x| x+2}))
I know that most probably this defeats the purpose of your question but I can't see any other way around it - it's not that you specify which method to be called, you just pass it something that responds to to_proc.
There is another native option for enumerables which is pretty only for two arguments in my opinion. the class Enumerable has the method with_object which then returns another Enumerable.
So you can call the & operator for a method with each item and the object as arguments.
Example:
a = [1,3,5,7,9]
a.to_enum.with_object(2).map(&:+) # => [3, 5, 7, 9, 11]
In the case you want more arguments you should repeat the proccess but it's ugly in my opinion:
a = [1,3,5,7,9]
a.to_enum.with_object(2).map(&:+).to_enum.with_object(5).map(&:+) # => [8, 10, 12, 14, 16]
Short answer: No.
Following #rkon's answer, you could also do this:
a = [1,3,5,7,9]
a.map &->(_) { _ + 2 } # => [3, 5, 7, 9, 11]
if all your method needs as argument is an element from the array, this is probably the simplest way to do it:
def double(x)
x * 2
end
[1, 2, 3].map(&method(:double))
=> [2, 4, 6]
Instead of patching core classes yourself, as in the accepted answer, it's shorter and cleaner to use the functionality of the Facets gem:
require 'facets'
a = [1,3,5,7,9]
a.map &:+.(2)
I'm surprised no one mentioned using curry yet, which has been in Ruby since Ruby 2.2.9. Here's how it can be done in the way OP wants using the standard Ruby library:
[1,3,5,7,9].map(&:+.to_proc.curry(2).call(11))
# => [12, 14, 16, 18, 20]
You need to supply an arity to curry that matches the call, though. This is because the interpreter doesn't know which object the + method refers to yet. This also means you can only use this when all the objects in map have the same arity. But that's probably not an issue if you're trying to use it this way.
I'm not sure about the Symbol#with already posted, I simplified it quite a bit and it works well:
class Symbol
def with(*args, &block)
lambda { |object| object.public_send(self, *args, &block) }
end
end
(also uses public_send instead of send to prevent calling private methods, also caller is already used by ruby so this was confusing)

accessing variables in loaded source while in irb

Say I have a file named test1.rb with the following code:
my_array = [1, 2, 3, 4 5]
Then I run irb and get an irb prompt and run "require 'test1'. At this point I am expecting to be able to access my_array. But if I try to do something like...
puts my_array
irb tells me "my_array" is undefined. Is there a way to access "my_array"
like this:
def my_array
[1, 2, 3, 4, 5]
end
You can also require your script and access that data in a few other ways. A local variable cannot be accessed, but these other three data types can be accessed within the scope, similar to the method definition.
MY_ARRAY = [1, 2, 3, 4 5] #constant
#my_array = [1, 2, 3, 4 5] #instance variable
##my_array = [1, 2, 3, 4 5] #class variable
def my_array # method definition
[1, 2, 3, 4 5]
end
No, there isn't. Local variables are always local to the scope they are defined in. That's why they are called local variables, after all.
In irb:
eval(File.read('myarray.rb'),binding)
Or you could drop to irb

Resources