so I posted a question earlier about displaying factors of non-prime numbers and got this as a solution.
Below is a part of the code, but I have a little bit trouble understanding a few terms in them (since I am relatively new to ruby).
def factors(n)
(1..n/2).select{|e| (n%e).zero?}.push(n)
end
For instance,
What does the method select do in general?
What does .zero? do?
Then,
puts "#{n} is not a prime number =>#{factors(n).join(',')}"
What does .join(',') do?
It would be greatly appreciated if anyone can explain these terms to me in basic terms or simple concepts.
select method filters a collection. You specify the condition (the predicate) in the block and select returns items who match that condition.
[1,2,3,4].select(&:even?)
=> [2, 4]
i.zero? is another way to write i == 0
[0,2,3,0].select(&:zero?)
=> [0, 0]
join method concatenate a collection as a string with the parameter as a separators between items
[0,2,3,0].select(&:zero?).join(' and ')
=> "0 and 0"
Note
[1,2,3].select(&:even?)
is a simpler way to write
[1,2,3].select { |item| item.even? }
i will try explain by following links and text from documentation
join()
Returns a string created by converting each element of the array to a string, separated by the given separator. If the separator is nil, it uses current $,. If both the separator and $, are nil, it uses empty string.
[ "a", "b", "c" ].join #=> "abc"
[ "a", "b", "c" ].join("-") #=> "a-b-c"
select
Returns a new array containing all elements of ary for which the given block returns a true value.
If no block is given, an Enumerator is returned instead.
[1,2,3,4,5].select { |num| num.even? } #=> [2, 4]
a = %w{ a b c d e f }
a.select { |v| v =~ /[aeiou]/ } #=> ["a", "e"]
zero?
zero? → true or false
Returns true if num has a zero value.
Ruby html documentation: ruby-doc.org
Related
Have the following code which should select every other character of a string and make a new string out of them:
def bits(string)
string.chars.each_with_index.select {|m, index| m if index % 2 == 0}.join
end
However, select returns this output with test case "hello":
"h0l2o4"
When using map instead I get the desired result:
"hlo"
Is there a reason why select would not work in this case? In what scenarios would it be better to use map over select and vice versa
If you still want to use select, try this.
irb(main):005:0> "hello".chars.select.with_index {|m, index| m if index % 2 == 0}.join
=> "hlo"
each_with_index does not work because it is selecting both the character and the index and then joining all of that.
The reason that select does not work in this case is that select "Returns an array containing all elements of enum for which the given block returns a true value" (see the doc here), so what you get in your case is an array of arrays [['h',0],['l',2],['o',4]] which you then join to get "h0l2o4".
So select returns a subset of an enumerable. map returns a one to one mapping of the provided enumerable. For example the following would "fix" your problem by using map to extract character from each value returned by select.
def bits(string)
string.chars.each_with_index.select {|m, index| m if index % 2 == 0}.map { |pair| pair.first }.join
end
puts(bits "hello")
=> hlo
For lots of reasons this is not a good way to get every other character from a string however.
Here is another example using map. In this case each index is mapped to either the character or nil then joined.
def bits(string)
string.chars.each_index.map {|i| string[i] if i.even? }.join
end
If you use Enumerable#map, you will return an array having one element for each character in the string.
arr = "try this".each_char.map.with_index { |c,i| i.even? ? c : nil }
#=> ["t", nil, "y", nil, "t", nil, "i", nil]
which is the same as
arr = "try this".each_char.map.with_index { |c,i| c if i.even? }
#=> ["t", nil, "y", nil, "t", nil, "i", nil]
My initial answer suggested using Array#compact to remove the nils before joining:
arr.compact.join
#=> "tyti"
but as #npn notes, compact is not necessary because Array#join applies NilClass.to_s to the nil's, converting them to empty strings. Ergo, you may simply write
arr.join
#=> "tyti"
Another way you could use map is to first apply Enumerable#each_cons to pass pairs of characters and then return the first character of each pair:
"try this".each_char.each_cons(2).map(&:first).join
#=> "tyti"
Even so, Array#select is preferable, as it returns only the characters of interest:
"try this".each_char.select.with_index { |c,i| i.even? }.join
#=> "tyti"
A variant of this is:
even = [true, false].cycle
#=> #<Enumerator: [true, false]:cycle>
"try this".each_char.select { |c| even.next }.join
#=> "tyti"
which uses Array#cycle to create the enumerator and Enumerator#next to generate its elements.
One small thing: String#each_char is more memory-efficient than String#chars, as the former returns an enumerator whereas the latter creates a temporary array.
In general, when the receiver is an array,
use map when you want to return an array containing one element for each element of the receiver.
use Enumerable#find when you want to return just one element of the receiver.
use Array#select or Array#reject (or Enumerable#select or Enumerable#reject if the receiver is an enumerator).
Me, I'd use a simple regular expression:
"Now is the time to have fun.".scan(/(.)./).join
#=> "Nwi h iet aefn"
Constructing a basic address book in Ruby. I have the following line of code in my program that iterates over the existing array(#address_book) based on a standard numeric input (entrynumber) to match the array index. The resulting value that matches that index is then returned. Here's the code in question:
puts #address_book.entries.each_with_index.select {|val, i| i == (entrynumber - 1)}
the results look great except that the index is also returned at the bottom, like this: (note 0 at the end of return) I'd ideally like the index number itself at the bottom not returned.
View by Entry Number
Entry Number: 1
You picked 1
Name: adam adams
Phone Number: 111-111-1111
Email: aa#aa.com
0
What am I missing in terms of returning the value, but without the index?
The problem
The trouble is that each_with_index is turning #address_book.entries into an array of arrays. Here's an example of what I mean:
["a", "b"].each_with_index.to_a
# => [["a", 0], ["b", 1]]
So when you apply select to each_with_index, the selected elements are each going to be an array with the element and its index:
["a", "b"].each_with_index.select { |e, i| i == 1 }
=> [["b", 1]]
A bad fix
You could fix that by using #map to select only the first element of each selected row:
["a", "b"].each_with_index.select { |e, i| i == 1 }.map(&:first)
=> ["b"]
Using select.with_index
Better still, you could use select.with_index:
["a", "b"].select.with_index { |e, i| i == 1}
=> ["b"]
Or, in the case of your code:
#address_book.entries.
each_with_index.select.with_index {|val, i| i == (entrynumber - 1)}
Using Array#[]
If #address_book.entries is an array, then you can index the array, not using select at all:
#address_book_entries[entrynumber - 1]
If it's not an array, you can turn it into one with #to_a:
#address_book.entries.to_a[entrynumber - 1]
However, if #address_book.entries is large, this could use a lot of memory. Be careful when turning an enumeration into an array.
It seems like what you want it to get a single item which isn't really what select is best suited for (especially when you're retrieving it via an index. I would probably do something like:
#address_book.entries.to_a[entrynumber - 1]
How would I write a case statement that would list all elements in an array, allow the user to pick one, and do processing on that element?
I have an array:
array = [ 'a', 'b', 'c', 'd' ]
Ultimately I'd like it to behave like this:
Choices:
1) a
2) b
3) c
4) d
Choice =>
After the user picks 3, I would then do processing based off the choice of the user. I can do it in bash pretty easily.
Ruby has no built-in menu stuff like shell scripting languages do. When doing menus, I favor constructing a hash of possible options and operating on that:
def array_to_menu_hash arr
Hash[arr.each_with_index.map { |e, i| [i+1, e] }]
end
def print_menu menu_hash
puts 'Choices:'
menu_hash.each { |k,v| puts "#{k}) #{v}" }
puts
end
def get_user_menu_choice menu_hash
print 'Choice => '
number = STDIN.gets.strip.to_i
menu_hash.fetch(number, nil)
end
def show_menu menu_hash
print_menu menu_hash
get_user_menu_choice menu_hash
end
def user_menu_choice choice_array
until choice = show_menu(array_to_menu_hash(choice_array)); end
choice
end
array = %w{a b c d}
choice = user_menu_choice(array)
puts "User choice was #{choice}"
The magic happens in array_to_menu_hash:
The [] method of Hash converts an array with the form [ [1, 2], [3, 4] ] to a hash {1 => 2, 3 => 4}. To get this array, we first call each_with_index on the original menu choice array. This returns an Enumerator that emits [element, index_number] when iterated. There are two problems with this Enumerator: the first is that Hash[] needs an array, not an Enumerator. The second is that the arrays emitted by the Enumerator have the elements in the wrong order (we need [index_number, element]). Both of these problems are solved with #map. This converts the Enumerator from each_with_index into an array of arrays, and the block given to it allows us to alter the result. In this case, we are adding one to the zero-based index and reversing the order of the sub-arrays.
I am getting confused with the Array methods below. Can anyone help me understand how differently they work from each other with the help of simple snippet?
array.sort and array.sort { | a,b | block }
array.to_a and array.to_ary
array.size and array.length
array.reverse and array.reverse_each {|item| block }
array.fill(start [, length] ) { |index| block } and
array.fill(range) { |index| block }
Please read the documentation for Array.
sort:
a=[3,1,2]
a.sort # => [1, 2, 3]
a.sort{|a,b| b<=>a} # => [3, 2, 1]
use the second one if you need some custom way to sort elements.
to_a vs. to_ary:
class Foo < Array;end
b=Foo[1,2]
b.to_ary.class # returns self
b.to_a.class # converts to array
size and length are exactly the same.
reverse_each is pretty much the same as reverse.each.
If you want to fill only a part of the array, you can call Array.fill either with a range or start,length. Those are just different ways to achieve the same:
(["a"]*10).fill("b",2..7)
(["a"]*10).fill("b",2,6)
both return ["a", "a", "b", "b", "b", "b", "b", "b", "a", "a"].
I have an array arr. I want to destructively remove elements from arr based on a condition, returning the removed elements.
arr = [1,2,3]
arr.some_method{|a| a > 1} #=> [2, 3]
arr #=> [1]
My first try was reject!:
arr = [1,2,3]
arr.reject!{|a| a > 1}
but the returning blocks and arr's value are both [1].
I could write a custom function, but I think there is an explicit method for this. What would that be?
Update after the question was answered:
partition method turns out to be useful for implementing this behavior for hash as well. How can I remove elements of a hash, returning the removed elements and the modified hash?
hash = {:x => 1, :y => 2, :z => 3}
comp_hash, hash = hash.partition{|k,v| v > 1}.map{|a| Hash[a]}
comp_hash #=> {:y=>2, :z=>3}
hash #=> {:x=>1}
I'd use partition here. It doesn't modify self inplace, but returns two new arrays. By assigning the second array to arr again, it gets the results you want:
comp_arr, arr = arr.partition { |a| a > 1 }
See the documentation of partition.
All methods with a trailing bang ! modify the receiver and it seems to be a convention that these methods return the resulting object because the non-bang do so.
What you can to do though is something like this:
b = (arr.dup - arr.reject!{|a| a>1 })
b # => [2,3]
arr #=> [1]
Here is a link to a ruby styleguide which has a section on nameing - although its rather short
To remove (in place) elements of array returning the removed elements one could use delete method, as per Array class documentation:
a = [ "a", "b", "b", "b", "c" ]
a.delete("b") #=> "b"
a #=> ["a", "c"]
a.delete("z") #=> nil
a.delete("z") { "not found" } #=> "not found"
It accepts block so custom behavior could be added, as needed