小编Wm.*_*ite的帖子

Ruby方法来反转字符串输入

我不明白为什么revers_string = string [i] + reversed_string将最后一个char放在第一位.似乎string [i]将索引第一个char而不是最后一个.因此,如果字符串是"abc",则索引0将是'a'而不是'c'.有人可以解释ruby如何从索引0获取'c'吗?然后,当然,指数1的'b'?等等

编写一个将字符串作为输入的方法,并以相反的顺序返回具有相同字母的新字符串.

难度:容易.

def reverse(string)
  reversed_string = ""

  i = 0
  while i < string.length
    reversed_string = string[i] + reversed_string

    i += 1
  end

  return reversed_string
end
puts("reverse(\"abc\") == \"cba\": #{reverse("abc") == "cba"}")
puts("reverse(\"a\") == \"a\": #{reverse("a") == "a"}")
puts("reverse(\"\") == \"\": #{reverse("") == ""}")
Run Code Online (Sandbox Code Playgroud)

ruby string reverse

2
推荐指数
1
解决办法
2620
查看次数

我怎么算元音?

我已经看到了解决方案,它或多或少匹配

Write a method that takes a string and returns the number of vowels
 in the string. You may assume that all the letters are lower cased. You can treat "y" as a consonant.
Difficulty: easy.

def count_vowels(string)
    vowel = 0
    i = 0
    while i < string.length  
        if (string[i]=="a" || string[i]=="e" || string[i]=="i" || string[i]=="o"|| string[i]=="u")
            vowel +=1
end

    i +=1

return vowel

end

puts("count_vowels(\"abcd\") == 1: #{count_vowels("abcd") == 1}")
puts("count_vowels(\"color\") == 2: #{count_vowels("color") == 2}")
puts("count_vowels(\"colour\") == 3: …
Run Code Online (Sandbox Code Playgroud)

ruby string

1
推荐指数
2
解决办法
1万
查看次数

标签 统计

ruby ×2

string ×2

reverse ×1