Ruby if else statement [closed] - ruby

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 5 years ago.
Improve this question
I am being asked to:
Define a method called first_longer_than_second with a parameter called first and another called second. The method will return true if the first word passed in is greater than or equal to the length of the second word. It returns false otherwise.
This is the code I have come up with:
def first_longer_than_second(first, second)
if first >= second
return true;
else
return false;
end
end
The calls I am making:
first_longer_than_second('pneumonoultramicroscopicsilicovolcanoconiosis', 'k') #=> false
first_longer_than_second('apple', 'prune') #=> true
For some reason on repl.it I only get the output false
And i get this error message on the platform I am actually meant to be completing this task on:
expected #<TrueClass:20> => true
got #<FalseClass:0> => false
Compared using equal?, which compares object identity,
but expected and actual are not the same object. Use
`expect(actual).to eq(expected)` if you don't care about
object identity in this example.
exercise_spec.rb:42:in `block (2 levels) in <top (required)>'
Tried a number of things, but annoyingly stuck with something that seems should be simple...

Define a method called first_longer_than_second with a parameter called first and another called second. The method will return true if the first word passed in is greater than or equal to the length of the second word. It returns false otherwise.
Your code:
def first_longer_than_second(first, second)
if first >= second
return true;
else
return false;
end
end
First of all, your code doesn't follow the requirements. They ask to compare the lengths of the two arguments. The if condition should be:
if first.length >= second.length
See the documentation of String#length.
Regarding the syntax of Ruby, the semicolons (;) after the statements are not needed. Like in Javascript, a Ruby statement can be terminated using a semicolon but also a newline. The semicolon is useful to separate two statements on the same line.
Next, the same as in Javascript (and many other languages), you can directly return the result of the comparison (and not put it into an if statement that returns true/false):
def first_longer_than_second(first, second)
return first.length >= second.length
end
One last improvement to make it look like Ruby (and not Javascript or PHP): a Ruby function returns the value of the last expression it computes; this makes the presence of the return keyword superfluous here.
Your code should be:
def first_longer_than_second(first, second)
first.length >= second.length
end

Related

What does "!" symbol mean in Ruby language [duplicate]

This question already has answers here:
Exclamation points before a variable in Ruby
(3 answers)
Closed 2 years ago.
For example: what is this saying:
if !result[movie[:studio]]
result[movie[:studio]] = movie[:worldwide_gross]
else
result[movie[:studio]] += movie[:worldwide_gross]
end
i += 1
end
This is a solution to manipulating an NDS, or rather getting some information from an NDS and I can't seem to find what the !result means.
The ! negates the element. So if result[movie[:studio]] is truthy then !result[movie[:studio]] is the opposite, falsy. Your conditional statement is basically saying that if there is no value for the studio key then give it a value of movie[:worldwide_gross], otherwise add to the current value.
If you do not like the ! you could consider using unless instead or swap the order of the conditional.
if result[movie[:studio]]
result[movie[:studio]] += movie[:worldwide_gross]
else
result[movie[:studio]] = movie[:worldwide_gross]
end
! negates the element as it was already mentioned.
So, !true => false
So if you do
if !hungry
do x
end
You will execute X if you are not hungry.
It might also be used on null. So you can use it to check if "not null". This might be the use case that you're seeing.

Explanation needed for this Ruby challenge [closed]

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 7 years ago.
Improve this question
I need some help understanding this code:
def SimpleAdding(num)
sum = 0
(num + 1).times do |x|
sum = sum + x
end
return sum
end
SimpleAdding(12) #=> 78
SimpleAdding(140) #=> 9870
I am not sure of the method. Why is the method written the way it is? Why is sum on the first line set to 0? And why is sum = sum + x used on the third line?
In Ruby, the def keyword delimits the start of a method, in your case named SimpleAdding. It takes one argument (in the parentheses) named num.
In the method body, the variable sum is given the initial value of 0.
The line containing (num + 1).times do |x| tells Ruby to execute the code between the do and end keywords a set number of times (an iterator), in this case num + 1. Remember, num represents the value received in the form of an argument when the method was called.
On the next line, the variable sum (initialized to 0 at the beginning of the method) is assigned the value of itself plus x.
Next line, our iterator ends.
Finally, we return the value stored inside of the variable sum.
And, the end of our method.
Enjoy learning Ruby!

Ruby Methods and Method calls? [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 8 years ago.
Improve this question
I am following a beginners course on Ruby, trying to define two methods in the editor:
A greeter method that takes a single string parameter, name, and returns a string greeting that person. (Make sure to use return and don't use print or puts.)
A by_three? method that takes a single integer parameter, number, and returns true if that number is evenly divisible by three and false if not.
The error I'm getting is "unexpected end".
def greeter(name)
return "hey" + name + "how are you" + "."
end
greeter(alan)
def by_three?(number)
if number % 3 == 0
return true
else
return false
end
by_three?(12)
You should terminate if statement with end keyword:
def by_three?(number)
if number % 3 == 0
return true
else
return false
end
end
Having said that, this method is written really bad, and it can be much simpler:
def by_three?(number)
number % 3 == 0
end

doubts regarding "||=" OR EQUALS operator in ruby [duplicate]

This question already has answers here:
What does ||= (or-equals) mean in Ruby?
(23 answers)
Closed 8 years ago.
I have some doubts regarding OR EQUALS (||=) operator in ruby. How does ruby interpreter implement it? Here is a sample of code:
class C
def arr
#num ||= []
end
end
When we use OR EQUALS operator in this circumstances, the first call to this method initializes the variable and adds an element, that's fine. When a second call is made to arr, how does it know that array has one element in it..
In Ruby, there are two values that are considered logical false. The first is the boolean value false, the other is nil. Anything which is non-nil and not explicitly false is true. The first time though the method, #num is nil, which is treated as false and the logical or portion of ||= needs to be evaluated and ends up assigning the empty array to #num. Since that's now non-nil, it equates to true. Since true || x is true no matter what x is, in future invocations Ruby short circuits the evaluation and doesn't do the assignment.
In general terms x ||= y is equivalent to x = x || y, it's just shorthand. It's implemented as the expanded form, same as &&=, += or -=.
Most programming languages, Ruby included, will stop executing a logical comparison statement like || on the first true value it encounters and return that. Likewise, it will halt on the first false value when using &&.
In general terms:
false || foo()
This will return false and not evaluate foo().
The pattern is best described as a "lazy initializer", that is the variable is defined only once, but only when it's actually used. This is in contrast to an "eager initializer" that will do it as early as possible, like inside the initialize method.
You'll see other versions of this pattern, like:
def arr
#num ||= begin
stuff = [ ]
# ...
stuff
end
end
This handles cases where the initial value is not as trivial and may need some work to produce. Once again, it's only actually generated when the method is called for the first time.
How does Ruby know on the second pass to not initialize it again? Simple, by that point #num is already defined as something.
As a note, if you're using values like false that would evaluate as non-true, then ||= will trigger every time. The only two logically false values in Ruby are nil and false, so most of the time this isn't an issue.
You'll have to do this the long-form way if you need to handle false as well:
def arr
return #num unless num.nil?
#num = false
end
There was talk of adding an ||=-like operator that would only trigger on nil but I don't think that has been added to Ruby yet.

Why the value of the assignment is always the value of the parameter? [duplicate]

This question already has an answer here:
Why isn't `method=` treated the same as any other method?
(1 answer)
Closed 6 years ago.
Would someone care to explain why in older versions of Ruby, the result of the assignment was the value returned by the attribute-setting method, but after Ruby 1.8, the value of the assignment is always the value of the parameter; the return value of the method is discarded. In the code that follows, older versions of Ruby would set result to 99. Now result will be set to 2.
class Test
def val=(val)
#val = val
return 99
end
end
t = Test.new
result = (t.val = 2)
result # => 2
What was the reasoning behind this change?
It's not uncommon to chain assignments together when you want to assign the same value to multiple variables. This is even more common in other languages.
#user_id = user.id = next_user_id
But what happens when you aren't thinking about that, and so the return value isn't the same as the input value?
class User
def id=(name)
#id = name
#modified = true
end
def modified?
#modified
end
end
This code will work totally fine until one day when you go drop it in an assignment chain like the above, when all of a sudden you'll get unexpected results.
So, the interpreter does some sort of voodoo and ensures that the RHS of the assignment is the return value, discarding the actual return value.
Assignments always evaluate to the assigned value. That's a simple and consistent rule, both consistent within Ruby itself, as well as consistent with most other expression-based programming languages.
Everything else would be an inconsistent special case, and those are bad.

Resources