0
0

More than 1 year has passed since last update.

Railsのcase文で色々遊ぶ

Posted at

遊ぶ

暇だったので色々rubyの問題を解いていたのだが、こういう簡単なお題でも色々書き方があって面白い。

#### ルール
下記4つの文字列をもとに計算するメソッドを作る。

iは値を+1
dは値を-1
sは値を二乗
oは値を配列に出力

#### 条件
1. メソッド名はparseで、ランダムなStringの値が引数としてくる。
2. idso以外の文字列も引数として与えられるため、紛れ込んでても対応する

テストの値

    expect(parse("ooo")).to eq([0, 0, 0])
    expect(parse("iiisdoso")).to eq([8, 64])
    expect(parse("ioioio")).to eq([1, 2, 3])
    expect(parse("idoiido")).to eq([0, 1])
    expect(parse("isoisoiso")).to eq([1, 4, 25])
    expect(parse("codewars")).to eq([0])

答え

答え1

def parse(data)
  list = []
  sum = 0

  data.split('').each do |x|
    case x
    when "i"
      sum += 1
    when "d"
      sum -=1
    when "s"
      sum = sum * sum
    when "o"
      list << sum
    end
  end

  list
end

答え2
俺的には答え2の方がclassとか使ってて色々応用効きそうなソースコードで好き。
メソッド定義するだけだから答え1で問題ないけれども。

class Deadfish
  def initialize (commands)
    @result = []
    @current = 0
    @commnads = commands.chars
  end
  
  def i; @current += 1 end
  def d; @current -= 1 end
  def s; @current *= @current end
  def o; @result << @current end
  
  def method_missing *; end
  
  def parse
    @commnads.each{|cmd| send cmd}
    @result
  end
end

def parse(data)
  Deadfish.new(data).parse
end
0
0
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
0