0

I want to set the value of a equal to the index found unless that index is zero, in which case I want to set it to some number minus that value. I am wondering if it is possible to perform this action (taken from python) in Ruby:

a='/-123456789X'.find(y)or 99-x

Does anyone know of a good way to do this?

2
  • Can you clarify a bit? Not 100% what you want here Commented Jul 12, 2018 at 21:22
  • Sometimes the best solution is the most straightforward: idx = str.index(substr); idx = 99 if idx == 0. Note that 99 minus zero is 99 and str.index(substr) #=> nil if str does not contain the substring substr. Commented Jul 13, 2018 at 2:57

2 Answers 2

2

Try this one. Given x and y

a = "/-123456789X".index(y) || 99 - x
Sign up to request clarification or add additional context in comments.

1 Comment

Here's the docs for String#index. And an important difference between Ruby and Python (and many other languages) is that 0 is not false. Only false and nil are false. In Python 0 or 99 is 99. In Ruby 0 || 99 is 0.
1

In string.find(other) will return the index of other or -1 if other does not exist in string.

In string.index(other) will return the index of other or nil if other does not exist in string.

"Truthy" and "Falsey" values:

  • ruby acknowledges nil as "falsey" and 0 as "truthy"; but
  • python acknowledges 0 as "falsey" and -1 as "truthy"

So your current python code has 3 possible return values:

  • -1 (non-existent sub-string)
  • 99 - x (existent sub-string starting with '/')
  • n (index of existent sub-string that does not start with '/')

In order to achieve an equivalent result in ruby your code could look like this:

str = '/-123456789X'
a = if y.start_with?('/') && str.index(y)
  99 - x
else
  str.index(y) || -1
end

Other alternatives include:

# Ruby >= 2.5 using `String#match? 
str.match?(/\A#{y}/) ? 99 - x : str.index(y) || -1

That being said your actual request "I want to set the value of a equal to the index found unless that index is zero, in which case I want to set it to some number minus that value" seems a little different and I am not sure if this means that x is "that value" and what x should represent in that case.

  • Should x be the begining index?
  • Should x be the ending index?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.