Ruby 기초 - 문법과 기본 개념

Published: (December 30, 2025 at 11:42 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

Ruby 프로그래밍 언어의 기본 문법과 개념을 알아봅니다.

파일 및 실행

# 파일 형식: 파일명.rb
# 실행 방법: ruby 파일명.rb (확장자가 rb가 아니어도 실행 가능)

주석

# 한 줄 주석

=begin
여러 줄 주석
=end

줄바꿈 및 명령 구분

# 줄바꿈
puts \
  'hello'

# 명령 구분 (라인이 바뀌면 생략 가능)
puts 'hello'; puts 'world'

메서드 호출 및 객체 변형

a = 'aaaA'
a.downcase!
puts a  # "aaaa"

심볼

:심볼명

변수와 기본값

x = 10

# 기본값 설정
@variable ||= "default value"

병렬 할당 (parallel assignment)

x, y, z = [true, 'two', false]

메서드 정의

파라미터 없는 경우

def hello
  'Hello'
end

파라미터 있는 경우

def hello1(name)
  'Hello ' + name
end
puts hello1('satish')

괄호 없이 파라미터 사용

def hello2 name2
  'Hello ' + name2
end
puts hello2 'talim'

파라미터 기본값 설정

def mtd(arg1="Dibya", arg2=arg1 + "Shashank", arg3="Shashank")
  "#{arg1}, #{arg2}, #{arg3}."
end

puts mtd
puts mtd("ruby")

메서드 별칭 (alias)

def oldmtd
  "old method"
end
alias newmtd oldmtd

def oldmtd
  "old improved method"
end

puts oldmtd   # "old improved method"
puts newmtd   # "old method"

가변 파라미터

def foo(*my_string)
  my_string.inspect
end

puts foo('hello', 'world')
puts foo()

논리 연산자

@var = @var || "first"
@var ||= "second"  # var이 없거나 false이면 "second" 사용

명령줄 인자

f = ARGV[0]
puts f

사용자 입력

city = gets.chomp  # chomp는 개행문자 제거
puts "The city is " + city

출력 메서드

puts 'Hello'  # 줄바꿈 포함
p 'hello'     # 구조를 출력
print 'hi'    # 줄바꿈 없음

난수 생성

rand(max_value)
Back to Blog

Related posts

Read more »

Ruby 제어문 - 조건문과 반복문

조건문 ruby s1 = 'Jonathan' s2 = 'Jonathan' s3 = s1 if s1 == s2 puts 'Both Strings have identical content' else puts 'Both Strings do not have identical content'...

Why Bash Syntax Feels So Arcane

Bash’s Historical Roots Bash runs deep beneath the surface of Linux. With only a line or two, it can take full control of your machine. It is often viewed by b...

Ruby 블록과 Lambda

Ruby 블록Block Ruby의 블록Block은 메서드 호출과 함께 코드 블록을 전달하는 방법입니다. ruby def call_block puts 'Start of method' yield yield puts 'End of method' end call_block { puts 'In...