ruby delete command misbehaving? [closed] - ruby

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Manipulating an array of integers is returning unexpected results with ruby 2.6.1p33 (2019-01-30 revision 66950) [x86_64-darwin13] :
a = [1, 126, 158, 201, 102]
=> [1, 126, 158, 201, 102]
b = 102
=> 102
a.delete(b)
=> 102
many slight variations of syntax always lead to the same result.
is the syntax mistaken, could there be some higher command that negates this command or worse, is some corruption issue at hand? How can this be ascerted?

From the Array#delete docs:
When no block is given, removes from self each element ele such that
ele == obj; returns the last deleted element...
In your case b is equal to 102, hence it prints its value after defining the variable. Then a.delete(b) corroborates that there's an element in a equals to b so it deletes it and returns the value of b.

What were you expecting to see as a result? The snippet you show seems to be working exactly as expected.
Examine the contents of a immediately after executing your code shown above - you should find that the final entry has been deleted.
The delete() method is perhaps defined in a slightly surprising way for Ruby. One might expect it to return the modified array and leave the original unchanged so that one could use it like this:
a.delete(b).delete(158)
and then for there to be a bang version which modifies the array in place:
a.delete!(b)
but that's not the way it's been defined. The basic delete() method modifies the array on which it's called.

Related

Create a Ruby method that applies an operation on arrays of integers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
EDIT: ok, I misunderstood the task. sorry.
I really can't find anything else on the web and don't get it myself.
I want to to delete the odd-numbered entries from an array of integers with a method in Ruby. But I get only errors right at the point where I define the method. How can I make the method understand this?
def even
a=[]
i=0
while i<=a.length
a[i]%2 == 1
a.delete(a[i])
i+=i
end
end
even([1,2,3])
You can simply use Ruby array reject method like below,
arr = [1,2,3,4,5,6,7,8]
arr.reject{|v| v%2 == 1}
# => [2, 4, 6, 8]
in ruby it is usually easier to think in a more functional way. In your case, you want to iterate through the list of elements, selecting the ones that are even. To iterate through a list and select elements using a predicate, use select. A number already has a method to check if it is even (even?). So the solution is quite simple:
[1,2,3].select(&:even?)
that returns a new list with only the even numbers. If you want to modify the list in place, use select! instead.

Use of block passed to Hash#fetch [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Hash#fetch returns the value in a hash for the given key.
It also accepts an optional block:
h = { "a" => 100, "b" => 200 }
h.fetch("a") #=> 100
h.fetch("z", "go fish") #=> "go fish"
h.fetch("z") { |el| "go fish, #{el}"} #=> "go fish, z"
One would assume that a block will help us work on the value associated with given the key. However, the block seems to yield the key instead of the value (refer to the third call of fetch above).
What is the use of such implementation? I don't see any point in key being passed to the block as it is already known; it is the value that one is interested in, as is evident by call to fetch.
UPDATE: This is invalid question, I misread the documentation. My apologies
The block is used for dealing with missing values - the value is not yielded because there isn't one.
You're supposed to use the key to return a suitable value (or raise an exception if appropriate)

How to select the last n % elements of an array in Ruby? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a sorted array and I would like to keep only the last 50-60-70% (generally n%) of the elements. How can I achieve this?
For example
[1,2,3,4,5,6,7,8,9].last(this.size*0.7)
doesn't work.
You need to use tap in order to reference the object like you want.
[1,2,3,4,5,6,7,8,9].tap { |this| break this.last(this.size*0.7) }
The break is needed because tap normally ignores the block's return value.
I don't know Ruby, but I can google and guess.
a = [1,2,3,4,5,6,7,8,9]
a[a.size * 0.6..-1] ==> [6, 7, 8, 9]
a.last(a.size * 0.4) ==> [7, 8, 9]
The reason for this is that you first have to give the array a name, before you can reference it. In this case, a.
You can look up the functionality like this in the relevant documentation: Array.
If you really want the functionality you are requesting you could use #tap which allows you to alter the method chain inside a block like this
[1,2,3,4,5,6,7,8,9].tap do |a|
#a is the original array passed into a block
a.delete_if.with_index{|index,element| element if index + 1 < a.size * 0.7}
end
#=> [4,5,6,7,8,9]
Please note this is destructive to the original array because you are tapping into it which does not seem like a concern since you are not storing the original array in a variable right now anyway.
Not sure why you would not want to store the array in a variable though as it makes the procedure far easier. A simple method like would suffice for this
def last_n_percent(array,percent=0.5)
array.last(array.size * percent)
end

Issue with my Ruby Assignment [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I am new to learn Ruby, I got an assignment from my teacher which I am trying to understand.
Here is the question. Consider the following code:
ary = Array.new(7, "--day")
ary[2] = "Tuesday"
ary[4] = "Thursday"
ary[7] = "Sunday"
ary[-1] = "Saturday"
puts ary[7]
puts ary[-4]
puts ary[-6, 2]
puts ary[2] = ary[7][-3,3]
puts ary.length
Why does this code produce 6 lines of output? Where did the extra line come from?
What is the value of ary[2] at the end?
Why is the length (or size) of the array different than when we constructed it?
I won't answer these questions directly, since it sounds like it's a homework assignment, but I will try to point you in the right direction.
Take a look at the documentation for Ruby's Array#[]. More specifically, take a look at which usages in your example code match the usages in the examples, and you might get a better idea of what's happening. Keep in mind that with Ruby, you can index from the end of your array by using negative index numbers.
Open up irb in the terminal and run the first 5 lines (all the ary[]= lines). Then run each of the puts lines individually and see what the output is. Keep in mind that lines with => something are the return values, not what is being printed.
Take a look at String#[], and try out the different parts of line 9 individually. For example, see what ary[7] does. Then see what ary[7][-3, 3] does. See what happens if you do "Any Random String"[a_number, another_number].
After you first create the array, check ary.length. Then run each of the following lines, checking ary.length after each subsequent assignment.
Don't get discouraged, and don't listen to people telling you to give up. This stuff can be confusing when you first start out, but getting familiar with where to find documentation, how to use the command line tools, and how to experiment will make it much easier to explore and discover what your code is doing, when, and why.
If you ever need to try and figure out what is going on in your code, just open up irb in your terminal and start playing around with it, and you should be able to answer most of your questions through experimentation.

Exceptions to the "Command-Query Separation" Rule?

Command-Query Separation "states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both. In other words, asking a question should not change the answer."
a = [1, 2, 3]
last = a.pop
Here, in Ruby, the pop command returns the item is popped off the Array.
This an example of a command and query within one method, and it seems necessary for it to be so.
If this is the case, is it really a code smell to have a method that is essentially a query as well as a command?
Stack popping is a well-known exception to CQS. Martin Fowler notes it as a good place to break the rule.
I would say in this case it's not a code smell, but in general it is a code smell.

Resources