0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Ruby】sliceの使い方 初級編

Posted at

概要

Rubyのドリルでsliceコードが回答として出て、なかなか理解ができなかったため備忘録として残します。

問題

任意の2つの文字列があります。
大文字と小文字の違いを無視して、どちらかの文字がもう一方の文字の最後にある場合はTrue
ない場合はFalseを出力するプログラムを作りましょう。
(つまり、大文字と小文字は区別されません)。

回答

Ruby
def end_other(a,b)
  a_down = a.downcase
  b_down = b.downcase
  a_len = a_down.length
  b_len = b_down.length
  if  a_down.slice!(-(b_len)..a_len - 1) == b_down #←この行を解説します!
    puts "True"
  else
    puts "False"
  end
end

puts "アルファベットを入力してください"
code = gets.chomp

puts "指定する文字を入力してください"
find_word = gets.chomp

end_other(code, find_word)

解説

sliceとは、指定した範囲を文字列から取り除いたうえで取り除いた部分文字列を返します。
とありました:grin:
参考:https://docs.ruby-lang.org/ja/2.3.0/method/String/i/slice=21.html

string = "this is a string"
string.slice!(2)        #=> "i"
string.slice!(3..6)     #=> " is "
string.slice!(/s.*t/)   #=> "sa st"
string.slice!("r")      #=> "r"

:warning:カウントは**0(ゼロ)**から始まります!
 私は、ここで躓きました:sweat:

よって、上記回答を詳細を説明すると下記のようになります:point_up:

解説
def end_other(a,b)
  a_down = a.downcase  
  #変数aの文字を全て小文字に変換!
  b_down = b.downcase
  #変数bの文字を全て小文字に変換!
  a_len = a_down.length
  #変数aの文字数を取得!
  b_len = b_down.length
  #変数bの文字数を取得!
  if  a_down.slice!(-(b_len)..a_len - 1) == b_down
  #-(b_len) :変数aの最後の文字から変数bの文字数分の文字を返します
  #a_len - 1 :変数aの最後の文字を返します
  #.. :以上、以下を表します
# 省略

こんな感じですが、正直 自分でも???という感じなので実際に文字を当て込んでいきます:grinning:

解説の解説www
a = wOrD
b = Rd

def end_other(a,b)
  a_down = a.downcase  
  #wOrD ⇒ word
  b_down = b.downcase
  #Rd ⇒ rd
  a_len = a_down.length
  #4文字
  b_len = b_down.length
  #2文字
  if  a_down.slice!(-(b_len)..a_len - 1) == b_down
  #-(b_len) :wordの後ろから2文字を返します・・・> r です
  #a_len - 1 :wordの最後の文字を返します・・・> d です
  #a_down.slice!(-(b_len)..a_len - 1) : rd となります

# 省略

少しわかりづらいかもしれません。。。。
文章力がなく申し訳ございません:bow:

少しでもお役に立てれば幸いです:laughing:

参考

sliceについて
..について

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?