yujiroのプログラミング

勉強内容をアウトプットし、サボらないようにする為のブログ

<DAY148> ドリルより

\ Follow me!! /

●7/19(金)
●学習日数 148日
●学習時間(本日)6時間
●累計学習時間 720.5時間
●一日あたりの平均学習時間 4.88時間

問題

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

※わからない場合はAPIを利用して問題を解きましょう。


出力例:
end_other('Hiabc', 'abc') → True
end_other('AbC', 'HiaBc') → True
end_other('abc', 'abXabc') → True

回答


時間切れ。
指定文字の後ろから3文字を返すメソッドを見つけられず。

def end_other(num1,num2)

 p num1.casecmp?(num2)

end

end_other('Hiabc', 'abc')

教科書回答

自分の考えと少し違うし、読みにくい。

def end_other(a,b)
  a_down = a.downcase
  b_down = b.downcase
  a_len = a_down.length
  b_len = b_down.length
  if  b_down.slice!(-(a_len)..b_len - 1) == a_down || a_down.slice!(-(b_len)..a_len - 1)
    puts "True"
  else
    puts "False"
  end
end

結局答えを考え出した

15分以内ではできなかったけど、この答えがしっくりきた。

def end_other(a,b)

 a_count = a.length
 b_count = b.length

  if a_count <= b_count
    check = b[-(a_count),b_count]
    p check.casecmp?(a)
  else
    check = a[-(b_count),b_count]
    p check.casecmp?(b)
  end
end

end_other('abcaaaa', 'abXabc')



参考文献

harry-the-cat.doorblog.jp