Ruby Method Conditions

The instructions for my program are to make a method that takes a string and returns a dash around any odd numbers, but with the exception that the end result cannot start or end with a dash "-". For example, if I enter "95601137", it should return

"9 - 5 - 6 0 - 1 - 1 - 3 - 7"

Here is the code:

def dashes(number)
  string = number.to_s
  i=0
  final = []
  while i<string.length
    digit = string[i].to_i
    if ((digit)%2 != 0) && (i==0) && (string.length == 1) && ((string.length - 1) == 0)
      final.push(string[i])
    elsif ((digit)%2 != 0) && (i==0) && (string.length != 1) && ((string.length - 1) > 0)
      final.push(string[i] + "-")
    elsif ((digit)%2 != 0) && (i>0) && (i!=(string.length - 1)) && ((string.length != 1))
      final.push("-" + string[i] + "-")
    elsif ((digit)%2 != 0) && (i!=0) && (i==(string.length - 1))
      final.push("-" + string[i])
    else final.push(string[i])
    end
    i+=1
  end
  return final
end

puts("Give me any number.")
answer = gets
puts dashes(answer)

My program has two problems:

  • When I enter 9, he returns "9-". Why?
  • When I enter a line that ends with an odd number, it puts a dash at the end, which she did not expect. I thought that my conditions ifwere strict as well.
+4
source share
5 answers

I would like to suggest another solution:

def dashes(num)
  str = num.to_s
  dashed_arr = str.chars.map.with_index do |digit, index|
    next digit if digit.to_i.even?
    if index.zero? # is it first digit?
      "#{digit} -"
    elsif index == str.length - 1 # is it last digit?
      "- #{digit}"
    else 
      "- #{digit} -"
    end
  end

  dashed_arr.join(' ').gsub('- -', '-')
end

puts dashes(95601137)
puts dashes(909)
# => "9 - 5 - 6 0 - 1 - 1 - 3 - 7"
# => "9 - 0 - 9"

:

  • str = num.to_s - , .. "95601137"
  • str.chars - . , : ["9", "5", "6", "0", "1", "1", "3", "7"], .
  • map , do ... end.

, :

[1, 2, 3].map do |num| 
  num * 2 
end
# => [2, 4, 6]

, .map.with_index ( ):

[1, 2, 3].map.with_index do |num, index| 
  num * index # index takes values 0, 1, 2
end 
# => [0, 2, 6]

, , digit 0- index.

  1. next digit if digit.to_i.even?. , . .to_i digit integer, . next digit .

  2. , , : , , , , :

    if index.zero? # first digit, index is zero-based
      "#{digit} -"
    elsif index == str.length - 1 # last digit
      "- #{digit}"
    else 
      "- #{digit} -"
    end
    
  3. dashed_arr, . : ["9 -", "- 5 -", "6", "0", "- 1 -", "- 1 -", "- 3 -", "- 7"]. , , .

  4. dashed_arr.join(' '). . : 9 - - 5 - 6 0 - 1 - - 1 - - 3 - - 7. , , .

  5. gsub: dashed_arr.join(' ').gsub('- -', '-'). gsub , , : 9 - 5 - 6 0 - 1 - 1 - 3 - 7.

! , , .

+2

, Cary Swoveland:

str = '95601137'

separators = str.each_char.map(&:to_i).each_cons(2).map do |pair| 
  pair.any?(&:odd?) ? ' - ' : ' '
end

str.chars.zip(separators).join
# => "9 - 5 - 6 0 - 1 - 1 - 3 - 7"
+2

:

answer = gets

:

answer = gets.strip

: 9

, 9 enter, : "9\n", 2. 9-. : gets.strip strip \n.

- ( ), chomp:

final_result = final.join('').chomp('-')

, - ( ), :

   if final_result[0] == '-'
    final_result[1..-1]
   else
    final_result
   end

(, ):

def dashes(number)
    string = number.to_s

    i = 0

    final = []

    while i < string.length

        digit = string[i].to_i

        if ((digit)%2 != 0) && (i==0) && (string.length == 1) && ((string.length - 1) == 0)             
            final.push(string[i])
        elsif ((digit)%2 != 0) && (i==0) && (string.length != 1) && ((string.length - 1) > 0)               
            final.push(string[i] + "-")
        elsif ((digit)%2 != 0) && (i>0) && (i!=(string.length - 1)) && ((string.length != 1))               
            final.push("-" + string[i] + "-")
        elsif ((digit)%2 != 0) && (i!=0) && (i==(string.length - 1))                
            final.push("-" + string[i])
        else 
            final.push(string[i])
        end

    i += 1

    end

   final_result = final.join('').gsub('--', '-').chomp('-')
   puts "final_result: #{final_result.inspect}"

   if final_result[0] == '-'
    final_result[1..-1]
   else
    final_result
   end
end

puts("Give me any number.")

answer = gets.strip

puts dashes(answer)

# > Give me any number.
# > 95601137
# > "9-5-60-1-1-3-7"
+1

:

str = "95601137"

String # each_char , # # peek:

enum = str.each_char

s = ''
loop do
  c = enum.next
  s << c
  n = enum.peek
  s << ((c.to_i.odd? || n.to_i.odd?) ? ' - ' : ' ')
end
s #=> "9 - 5 - 6 0 - 1 - 1 - 3 - 7"

, ('7') peek StopIteration. Kernel # loop .

String # gsub

gsub , , :

  • .

r = /       
    (\A\d) # match beginning of string followed by a digit, save in group 1
    |      # or
    (\d\z) # match a digit followed by end of string, save in group 2
    |      # or
    (\d)   # match a digit, save in capture group 3
    /x     # extended mode

str = "95601137"

str.gsub(r) do |s|
  if $1
    $1.to_i.odd? ? "#{$1}-"  : $1
  elsif $2
    $2.to_i.odd? ? "-#{$2}"  : $2 
  elsif $3
    $3.to_i.odd? ? "-#{$3}-" : $3
  else
    raise ArgumentError, "'#{s}' is not a digit" 
  end
end.gsub(/-+/, ' - ').gsub(/(\d)(\d)/,'\1 \2')
  #=> "9 - 5 - 6 0 - 1 - 1 - 3 - 7"
+1

A naive implementation, there may be more reasonable ways to do this:

def dashes(number)
  number                              # => 95601137
    .to_s                             # => "95601137"
    .chars                            # => ["9", "5", "6", "0", "1", "1", "3", "7"]
    .map(&:to_i)                      # => [9, 5, 6, 0, 1, 1, 3, 7]
    .map {|i| i.odd? ? "-#{i}-" : i } # => ["-9-", "-5-", 6, 0, "-1-", "-1-", "-3-", "-7-"]
    .join                             # => "-9--5-60-1--1--3--7-"
    .gsub(/^-|-$/, '')                # => "9--5-60-1--1--3--7"
    .gsub('--', '-')                  # => "9-5-60-1-1-3-7"
end
0
source

Source: https://habr.com/ru/post/1609354/


All Articles