티스토리 뷰

Ruby

ruby 소소한 tip

토마토계란 2023. 6. 20. 23:16
  • the simple way if check value is null

    • object&.spouse&.name == object.spouse.name if object && object.spouse
    • class << self
      1. Method defined within class << obj block will be added to the obj object.
      2. obj can be any object.
  • hash array sort by multiple condition

    arr = [{"count"=>2, "hit"=>2, "name"=>"1"},
      {"count"=>2, "hit"=>1, "name"=>"1"},
      {"count"=>1, "hit"=>5, "name"=>"1"}
    ]
    
    # sort
    sorted_arr = arr.sort_by {|data| [data["count"], data["hit"]]}
    
  • 결과

    [{"count"=>1, "hit"=>5, "name"=>"1"}, {"count"=>2, "hit"=>1, "name"=>"1"}, {"count"=>2, "hit"=>2, "name"=>"1"}]
  • it's different type

hash = {"count"=>2, "hit"=>2, "name"=>"1"}

hash.keys[0].class # => String

hash = {:count=>2, :hit=>2, :name=>"1"}

hash.keys[0].class # => Symbol
  • console에서 module reload

    • load "#{Rails.root}/lib/yourfile.rb"
  • module 도 변수를 가질 수 있다. 하지만 static member 와 유사

  • hash 를 다른 hash 로 만들 때 hash.inject({}) |m,e| 와 같이 사용

  • byebug

    • rake 든 rails 에서 실행하든 byebug 가 있으면 걸림
    • c : 다음 byebug 까지 실행
    • step: 한 줄씩 실행
  • is it good style to explicitly return in Ruby

    • 굳이 return 을 빼서 명료하지 않게 할 이유는 없음. return 을 명시해주는게 다른 개발자가 이해하기에도 좋음
  • find_by vs where

    • where 로 하면 string 으로 조건절 작성. 마지막에 take 를 하거나 each do end 문을 돌려야 함
    • find_by 는 하나만 가져옴
  • class vs module
    Screen Shot 2023-01-30 at 11 46 15

  • ruby hash array sort

'Ruby' 카테고리의 다른 글

ruby에서 exception 처리  (0) 2023.06.20
ActiveAdmin index column width 변경하는 방법  (0) 2023.06.20
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/12   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함